2

I'm implementing a custom controller as part of a plugin I'm building. There's some set up work that I'd like to do in the controller's constructor. I created a __construct method, and it seems to work as expected.

My question: Is there some reason that I should call parent::__construct() inside of the constructor? It requires an argument, which looks like it should be an ID of some sort, but I'm not sure where I should get that.

5

I'm not a huge fan of it but for this situation it might be more appropriate to use init(), Looking at Craft\BaseController:

/**
 * Initializes the controller.  This method is called by the Craft before the controller starts to execute.
 *
 * @throws HttpException
 * @return null
 */
public function init()
{

}

It seems a little odd to me to have a constructor for a controller though, what is it you're doing in it? Yii's Controller filters might be a better fit.

| improve this answer | |
  • 2
    +1 for using init() here. – Brad Bell Nov 25 '14 at 21:03
  • This sounds great. I was using __construct just because it's what I'm used to doing when extending a class. In many other languages or frameworks, it's required. I didn't know if the same was true here. Thanks for the heads up! – Gavin Anderegg Nov 25 '14 at 21:12
1

\Craft\BaseController extends \CController so if you want to have a custom constructor, you should accept the same parameters and call the parent constructor with them.

/**
 * @param string $id id of this controller
 * @param CWebModule $module the module that this controller belongs to.
 */
public function __construct($id, $module = null)
{
    parent::__construct($id, $module);
}
| improve this answer | |
  • Thanks coffe4u. I saw this as well, but I didn't know how to get the $id for my controller as I was constructing it, and I didn't know what I was supposed to pass back as the $module. I think the correct answer is to not use a constructor, but the init() method as suggested above. It's Brad Bell approved, which makes me feel pretty good about it :) – Gavin Anderegg Dec 12 '14 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.