【问题标题】:How to call shell function to another Controller - Cakephp如何调用 shell 函数到另一个控制器 - Cakephp
【发布时间】:2018-07-02 03:55:56
【问题描述】:

我在我的 shell 中使用这个函数来发送电子邮件

编辑: 用户Shell

<?php
namespace App\Shell;

use Cake\Console\Shell;
use Cake\Log\Log;
use Cake\Controller\Component;
use Cake\Controller\ComponentRegistry;
use App\Controller\Component\EmailComponent;

class UsersShell extends Shell
{
public function initialize()
{
    parent::initialize();
    $this->loadModel('Users');
    //Load Component 
    $this->Email = new EmailComponent(new ComponentRegistry());
}
public function mail()
{
    $to = 'exemple@gmail.com';
    $subject = 'Hi buddy, i got a message for you.';
    $message = 'User created new event';

    try {
        $mail = $this->Email->send_mail($to, $subject, $message);
        print_r($mail);
    } catch (Exception $e) {
        echo 'Message could not be sent. Mailer Error: ', $mail- 
 >ErrorInfo;
    }
    exit;   

}

我想知道如何在我的控制器中调用它?这里

编辑:事件位于插件文件夹中

事件控制器

<?php

namespace FullCalendar\Controller;

use FullCalendar\Controller\FullCalendarAppController;
use Cake\Routing\Router;
use Cake\Event\Event;
use Cake\Console\ShellDispatcher;

class EventsController extends FullCalendarAppController
{
public $name = 'Events';

public function add()
{
    $event = $this->Events->newEntity();
    if ($this->request->is('post')) {
        $event = $this->Events->patchEntity($event, $this->request->data);
        if ($this->Events->save($event)) {

           /* $shell = new ShellDispatcher();
            $output = $shell->run(['cake', 'users'], ['plugin' => 
           'Events']);

            if (0 === $output) {
            $this->Flash->success('Success from shell command.');
            } else {
            $this->Flash->error('Failure from shell command.'); */

            $this->Flash->success(__('The event has been saved.'));
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('The event could not be saved. Please, 
    try again.'));
        }
    }
    $this->set('eventTypes', $this->Events->EventTypes->find('list'));
    $this->set(compact('event'));
    $this->set('_serialize', ['event']);
    $this->set('user_session', $this->request->session()- 
 >read('Auth.User'));
    $this->viewBuilder()->setLayout('user');
}

如你所见,我使用了发送的 shell,我不确定它是否正确 但我失败了 谢谢!

编辑:

电子邮件组件

<?php
namespace App\Controller\Component;

use Cake\Controller\Component;
use Cake\Core\App;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require ROOT. '/vendor/phpmailer/phpmailer/src/Exception.php';
require ROOT. '/vendor/phpmailer/phpmailer/src/PHPMailer.php';
require ROOT. '/vendor/phpmailer/phpmailer/src/SMTP.php';

class EmailComponent extends Component {

public function send_mail($to, $subject, $message)
{
    // date_default_timezone_set('Asia/Calcutta');

    $sender = "exemple@gmail.com"; // this will be overwritten by GMail

    $header = "X-Mailer: PHP/".phpversion() . "Return-Path: $sender";

    $mail = new PHPMailer();

    $mail->SMTPDebug  = 2; // turn it off in production
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com'; 
    $mail->SMTPAuth = true;
    $mail->Username   = "exemple@gmail.com";  
    $mail->Password   = "xxxx";
    $mail->SMTPSecure = "tls"; // ssl and tls
    $mail->Port = 587; // 465 and 587

    $mail->SMTPOptions = array (
        'tls' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        ),
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

    $mail->From = $sender;
    $mail->FromName = "From Me";

    $mail->AddAddress($to);

    $mail->isHTML(true);
    $mail->CreateHeader($header);

    $mail->Subject = $subject;
    $mail->Body    = nl2br($message);
    $mail->AltBody = nl2br($message);

    // return an array with two keys: error & message
    if(!$mail->Send()) {
        return array('error' => true, 'message' => 'Mailer Error: ' . $mail->ErrorInfo);
    } else {
        return array('error' => false, 'message' =>  "Message sent!");
    }
}

}

【问题讨论】:

  • stackoverflow.com/questions/28511023/… 阅读此答案并用外壳替换组件,这将是相同的。发送电子邮件也应该是一个孤立的对象,而不是一个组件。好的架构是创建一个事件,有一个侦听器,在队列中创建一个条目以发送电子邮件,然后处理来自队列的电子邮件。队列是一个始终在后台运行的工作程序 shell。你的代码还有很多不适合这里的错误。

标签: shell email cakephp controller


【解决方案1】:

如果我错了,请纠正我。首先你的 shell 必须像这样启动。

class UsersShell extends AppShell { 

      public function main(){ //change name here to main
         $to = 'exemple@gmail.com';
         $subject = 'Hi buddy, i got a message for you.';
         $message = 'User created new event';

         try {
             $mail = $this->Email->send_mail($to, $subject, $message);
             print_r($mail);
         } catch (Exception $e) {
             echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
         }
         exit;   
     }       

}

顺便说一句,如果你想检查输出,你必须返回类似truefalse 的东西。否则,执行 shell 后检查输出是没有意义的。

【讨论】:

  • 不一定要检查我编辑的帖子,我不明白为什么它不工作,因为当我单独吃外壳时它工作正常
【解决方案2】:

首先检查在 CakePHP-CLI 中运行的 Shell 命令。像这样

bin/cake users mail

如果 shell 命令成功运行。贝壳类罚款。

接下来在Controller中使用Shell

<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Console\ShellDispatcher;

class PagesController extends AppController
{
    /**
     * Run shell command
     */
    public function run()
    {
        $shell = new ShellDispatcher();
        $output = $shell->run(['cake', 'users', 'mail']);
        // $output = $shell->run(['cake', 'users', 'mail', 'email']); // [pass arguments]
        // debug($output);

        if ($output === 0) {
            echo "Shell Command execute";
        } else {
            echo "Failure form shell command";
        }

        exit;
    }
}

更改Shell功能:如果邮件未发送运行$this-&gt;abort()函数并返回(int) 1并且邮件发送成功运行$this-&gt;out()函数并返回(int) 0

/**
 * Send Mail with shell command
 */
public function mail()
{
    $to = 'mail@gmail.com';
    $subject = 'Hi buddy, i got a message for you.';
    $message = 'Nothing much. Just test out my Email Component using PHPMailer.';

    $mail = $this->Email->send_mail($to, $subject, $message);
    // debug($mail);
    if ($mail['error'] === false) {
        $this->out("Mail Successfully Sent For :: ". $to);
    } else {
        $this->abort("Mail Error.");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    相关资源
    最近更新 更多