Is it possible to use the built-in CakePHP components (eg: EmailComponent
) as standalone classes?
I know this probably shows a design flaw, and that I'm not doing it the Cake way or something, but I have a class which is not tied to any Model/Controller and I want that to be able to send emails. Importing the EmailComponent doesn't work, since it tries to read information from $this->Controller
which is obviously null in this situation.
Any suggestions?
App::import('Core', 'Controller');
App::import('Component', 'Email');
$this->Controller =& new Controller();
$this->Email =& new EmailComponent(null);
$this->Email->initialize($this->Controller);
See comment 11 of EmailComponent in a (cake) Shell, should work for you.
Try using App::import.
App::import('Component', 'Email');
$email = new EmailComponent();
Note that you might need to pass null
as a parameter in the constructor since I think it might normally be expecting a reference to the controller. This might cause issues with regards to the EmailComponent
locating layouts and views though, you'll have to play around.
I'm pretty sure the cake way to do this is to make the component a vendor, if that's not too much of a pain. Then it would be accessible anywhere in the codebase. You could use this code in the beforeFilter and use it just like a component in your controller.
App::import('Vendor', 'EmailVendor');
$this->EmailVendor = new EmailVendor($this);
精彩评论