Cakephp 如何在Lib或Vendor文件中加载组件

Cakephp 如何在Lib或Vendor文件中加载组件,cakephp,cakephp-2.0,cakephp-2.3,Cakephp,Cakephp 2.0,Cakephp 2.3,我正在开发CakePHP2.3。我想将电子邮件组件加载到我的类中,该类位于Lib文件夹中。同样的情况下,供应商的文件也在此刻,我正在做的是 App::uses('EmailComponent', 'Controller/Component'); class Email { public static function sendemail($toEmail,$template,$subject) { $this->Email->smtpOptions = array(

我正在开发CakePHP2.3。我想将电子邮件组件加载到我的类中,该类位于Lib文件夹中。同样的情况下,供应商的文件也在此刻,我正在做的是

App::uses('EmailComponent', 'Controller/Component');
class Email { 

public static function sendemail($toEmail,$template,$subject) {
$this->Email->smtpOptions = array(
                            'port'=>'25',
                            'timeout'=>'30',

                            'host' => 'host',
                            'username'=>'username',
                            'password'=>'password'
                        );


        $this->Email->template = $template;
                        $this->Email->from    = 'no-reply@hello.com';
                        $this->Email->to      = $toEmail;
                        $this->Email->subject = $subject;
                        $this->Email->sendAs = 'both';

                        $this->Email->delivery = 'smtp';

                        $this->Email->send();



    }
我无法使用
$this
。。我得到了这个错误


$这不在对象上下文中时

$这可以在类中用于其on变量和类内定义的方法 在cakephp$中,当在控制器中定义$components数组时,在控制器中使用它

试试这个

$email = EmailComponent();
$email->$smtpOptions= array(); 

您不能这样做,组件是控制器的“扩展”,没有它们就不能使用它们

出于发送电子邮件的目的,请使用(电子邮件组件无论如何都不推荐使用)


在我的一个
Lib
类中,我用Cake 3克服了这个问题,使用了以下方法

$oRegistry  = new ComponentRegistry();
$oComponent = $oRegistry->load('PluginName.ComponentName');
我不确定这是否会与应用程序组件注册表的状态产生任何冲突;但是,就我而言,它似乎起了作用


希望这对某人有所帮助:)

谢谢您的回答。使用代码后会出现错误。。这里是“调用未定义的函数EmailComponent();”thaknow。。我在Lib文件夹中的类中使用这个吗?@hellosheikh你可以在任何地方使用
CakeEmail
类,所以是的,在你的库中使用它。
$oRegistry  = new ComponentRegistry();
$oComponent = $oRegistry->load('PluginName.ComponentName');