silverstripesilverstripe-4

Silverstripe override BlogController


I'm trying to override the blog module BlogController, just to use some ajax filtering. what I've got currently:

use SilverStripe\Core\Extension;
use SilverStripe\Control\Controller;

class BlogControllerExtension extends Extension
{
    private static $allowed_actions = [
        'category',
    ];
    public function category()
    {
        $category = $this->owner->getCurrentCategory();
        $request = Controller::curr()->getRequest();
        
        if ($category) {
            $this->owner->blogPosts = $category->BlogPosts();
            
            if ($request->isAjax()) {
                return $this->renderWith('Includes/BlogPosts', ['PaginatedList' => $this->blogPosts]);
            }
            return $this->render();
        }
        $this->httpError(404, 'Not Found');
        return null;
    }
}

If I add this isAjax code directly in the BlogController it works fine, but I can't get this to override - or am I just on the wrong track here?


Solution

  • Methods on an Extension don't ever override the method on the class being extended. You can add new methods/actions this way, but not replace existing ones.

    Probably the easiest way to do this would be to create a new class that subclasses BlogController and override the method in there - and then use dependency injection to replace the existing controller class with your new one:

    SilverStripe\Core\Injector\Injector:
      SilverStripe\Blog\BlogController:
        class: App\MyBetterBlogController