【问题标题】:how to load a component in Lib or Vendor files如何在 Lib 或 Vendor 文件中加载组件
【发布时间】:2013-12-09 22:48:22
【问题描述】:

我正在开发一个 cakephp 2.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.. 我收到此错误

$this 不在对象上下文中时

【问题讨论】:

    标签: cakephp cakephp-2.0 cakephp-2.3


    【解决方案1】:

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

    试试这个

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

    【讨论】:

    • 感谢您的回答。使用您的代码后出现错误..这里是“调用未定义函数 EmailComponent();”
    【解决方案2】:

    你不要那样做,组件是控制器的“扩展”,没有它们就不能使用。

    为了发送电子邮件,请使用CakeEmail class(无论如何,电子邮件组件已被弃用)。

    App::uses('CakeEmail', 'Network/Email');
    
    // ...
    
    $Email = new CakeEmail(array(
        'port'      => 25,
        'timeout'   => 30,
        'host'      => 'host',
        'username'  => 'username',
        'password'  => 'password',
        'transport' => 'Smtp'
    ));
    
    $Email->template($template)
          ->emailFormat('both')
          ->from('no-reply@hello.com')
          ->to($toEmail)
          ->subject($subject)
          ->send();
    

    【讨论】:

    • thaknyou.. 我在 Lib 文件夹中的课程中使用它吗?
    • @hellosheikh 你可以在任何地方使用CakeEmail 类,所以是的,在你的库中使用它。
    【解决方案3】:

    我能够在我的 Lib 课程之一中使用 Cake 3 克服这个问题...

    $oRegistry  = new ComponentRegistry();
    $oComponent = $oRegistry->load('PluginName.ComponentName');
    

    我不确定这是否会与应用程序组件注册表的状态产生任何不一致;但是,就我的目的而言,它似乎有效。

    希望这可以帮助某人:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-02
      • 2011-03-12
      • 2019-08-13
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 2019-02-06
      • 1970-01-01
      相关资源
      最近更新 更多