Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Correct approach for a 'base' controller ?
  • What would be the best approach for a 'base' controller which does the following tasks at every request?

    - Check if user is authenticated, redirects to auth page if not
    - Generate menu based on user rights
    - Add a pageview (optional)

    Should I make a controller, and extend that one instead of the normal controller, or a other approach?

  • HarroHarro
    Accepted Answer
    We use base classes for both controllers and models:

    \Module\Controller\Dashboard extends \Controller\Base extends \Controller_Template
    \Module\Model\User extends \Model\Base extends \Orm\Model

    (we use namespaces for all classes, no underscores, but the principle remains the same)

    We use the Theme class, replacing the basic view template. The base controller assigns all global stuff to the Theme instance, such as page template to use, headers, footers, sidebars, menu's, etc.

    We use Viewmodels to abstract all View specific code from both the View and the Controller, for example for menu generation.
  • philipptempelphilipptempel
    Accepted Answer
    I use base classes for both, controllers and models, as well.

    Then, it's the same as Harro already mentioned, the base controller instantiates the theme class, sets the actual theme that will be used, and sets the layout (controllers for admin specific tasks have different themes than the "public" controllers)

    Checking if a user is authenticated goes into a controller that does that in \Controller::before() while it can be that there are public pages that do not require login.

    I haven't yet worked with ViewModels in depth so I don't use them, however for e.g., breadcrumbs I am using an approach that can be found in e.g., fuelphp/fieldset (fuel v2 fieldset) that uses a renderer to render the breadcrumbs. And these renderers are basically theme specific, so I can do things like

    <?php
    $engine = new \Breadcrumb\Render\Bootstrap();
    echo $engine->render(\Model\Menu::for_user($user_id));
    ?>

    (this is probably somehow what Harro is doing with the ViewModels?!)

    The controllers are set up like so
      \Controller\Base extends \Controller
        \Controller\Authenticated extends \Controller\Base
          \Controller\Admin extends \Controller\Authenticated
    and one more
      \Controller\Widget extends \Controller\Base (controllers of this class only return output if they're called via HMVC requests, otherwise they throw a new \HttpNotFoundException())
  • Interesting, we use a similar setup, with Widget controllers returning theme partials (or not) via HMVC.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion