phalcon和yaf_使用Phalcon和Swift发送确认电子邮件

phalcon和yaf

Today, sending emails is considered the basic functionality of any web application. Usually, an email is sent to notify the user of some kind of activity that has taken place on the website, such as when he registers the account, updates information, or when new friends have been found. In this short tutorial I’ll show you how to send emails via Gmail quickly from within a Phalcon sample application. You can download the full source code from GitHub. We'll be building functionality which lets us send a confirmation email, and reacts to the click of said confirmation email.

今天,发送电子邮件已被视为任何Web应用程序的基本功能。 通常,会发送一封电子邮件以通知用户网站上已发生的某种活动,例如用户何时注册帐户,更新信息或何时发现新朋友。 在这个简短的教程中,我将向您展示如何在Phalcon示例应用程序中通过Gmail快速发送电子邮件。 您可以从GitHub下载完整的源代码。 我们将构建功能,使我们能够发送确认电子邮件,并对单击该确认电子邮件做出React。

步骤1:安装Phalcon,Phalcon工具 (Step 1: Install Phalcon, Phalcon Tools)

Installing Phalcon is easy if you just follow the instructions on their website. Don't forget to install the Phalcon tools as well!

如果只是按照Phalcon网站上的说明进行安装,则很容易。 不要忘记也安装Phalcon工具

If you're using Vagrant, you can also install the whole set into your box by following this tutorial.

如果您使用的是Vagrant,则还可以按照本教程的步骤将整个套件安装到盒子中。

步骤2:我们的应用程序的初始设置 (Step 2: Initial setup of our application)

We’ve successfully set up the development environment. Now we proceed to create the skeleton of our application. Open terminal (in Linux & Mac) or command prompt (cmd in Windows) and type following in the folder where you keep your web projects:

我们已经成功建立了开发环境。 现在,我们继续创建应用程序的框架。 打开终端(在Linux和Mac中)或命令提示符(在Windows中为cmd),然后在保存Web项目的文件夹中键入以下命令:

phalcon project sendmail

This will produce the following file and folder structure:

这将产生以下文件和文件夹结构:

sendmail project structure

Try it out. Open your web browser and type in http://127.0.0.1/sendmail/, or the address of the virtual host you gave to your project. Provided everything is running fine, as in the image below, continue to step 3.

试试看。 打开您的Web浏览器,然后输入http://127.0.0.1/sendmail/或您为项目提供的虚拟主机的地址。 如果一切正常,如下图所示,请继续执行步骤3。

enter image description here

步骤3:初始设定 (Step 3: Initial configuration)

There are a few things you need to configure at first:

首先需要配置以下几项:

  1. Database connection (app/config/config.php)

    数据库连接(app / config / config.php)
  2. Model, view, and controller directories

    模型,视图和控制器目录
  3. Base application URL

    基本应用程序URL
  4. Mail server configuration

    邮件服务器配置

All configurations are stored in the config.php file as per the image below:

所有配置均按照下图存储在config.php文件中:

config.php

Enter configuration settings as in the image above, only replace credentials with your own.

如上图所示输入配置设置,仅用您自己的凭据替换。

Regarding "mail", here I've left the driver set to smtp. I set the host to use smtp.gmail.com which is Gmail’s SMTP server. I set the port to 465 via SSL, and from to my email address, basically the same email address we'll be using to actually send the emails.

关于“邮件”,这里我将驱动程序设置为smtp。 我将主机设置为使用smtp.gmail.com ,这是Gmail的SMTP服务器。 我通过SSL设置端口465,并from我的电子邮件地址,基本上是相同的电子邮件地址,我们将使用实际发送的电子邮件。

步骤4:数据库架构和配置 (Step 4: Database schema and configuration)

The following schema shows 2 tables which we'll be using:

以下架构显示了我们将要使用的2个表:

CREATE TABLE IF NOT EXISTS `users` (
          `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
          `username` varchar(40) NOT NULL,
          `email` varchar(40) NOT NULL,
          `password` char(60) NOT NULL,
          `mustChangePassword` char(1) DEFAULT NULL,
          `fullName` varchar(50) NOT NULL,
          `active` char(1) DEFAULT NULL,
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

    CREATE TABLE IF NOT EXISTS `email_confirmations` (
          `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
          `usersId` int(10) unsigned NOT NULL,
          `code` char(32) NOT NULL,
          `createdAt` int(10) unsigned NOT NULL,
          `modifiedAt` int(10) unsigned DEFAULT NULL,
          `confirmed` char(1) DEFAULT 'N',
          PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

I leave out the details of how to create a database on purpose – it's assumed you know how to do this. Create a sample database with your favorite tool, and execute the above code against it.

我省略了有关如何有意创建数据库的详细信息-假定您知道如何执行此操作。 使用您喜欢的工具创建一个示例数据库,然后对它执行上面的代码。

A note about relationships here:

关于关系的注释:

  • The model “users” has many “email_confirmations”.

    模型“用户”具有许多“电子邮件确认”。
  • The model "email_confirmations" belongs to "users"

    模型“ email_confirmations”属于“用户”

Keep this in mind for later.

请记住这一点,以备后用。

步骤5:模型和验证 (Step 5: Models and validation)

A model is a class that extends Phalcon\Mvc\Model. It must be placed in the models directory. A model file must contain a single class; its class name should be in camel case notation and should correspond to the database table name. If, instead, you want to have a model User and a database table "users" you need to use the getSource method to configure this.

模型是扩展Phalcon \ Mvc \ Model的类。 它必须放置在models目录中。 模型文件必须包含一个类。 它的类名应采用驼峰表示法,并且应与数据库表名相对应。 相反,如果要拥有模型User和数据库表“ users”,则需要使用getSource方法进行配置。

We will now let Phalcon Tools generate the code for us. Using the command line and moving to your project’s directory, execute the following command:

现在,我们将让Phalcon Tools为我们生成代码。 使用命令行并移至项目目录,执行以下命令:

phalcon model users
    phalcon model email_confirmations

Let’s check out sample generated class Users for table users, and upgrade it accordingly:

让我们为表用户检出示例生成的类Users ,并相应地对其进行升级:

enter image description here

In the code above, we test if the login field validates against the rule Email. Additionally, we ensure that login is unique. Take note of the return statement which checks if validation has returned any validation messages.

在上面的代码中,我们测试登录字段是否针对规则Email进行验证。 此外,我们确保登录名是唯一的。 记下return语句,该语句检查验证是否返回了任何验证消息。

Let’s check out the generated class EmailConfirmations:

让我们检查一下生成的类EmailConfirmations

email_confirmation

The following code represents a very simple skeleton and I will only explain how afterCreate() and initialize() should look like – the rest of the code is available in the repository linked at the beginning of this article.

以下代码代表一个非常简单的框架,我将仅说明afterCreate()initialize()样子–其余代码可在本文开头链接的存储库中找到。

  1. The initialize() method is only called once during the request. In this method, Phalcon is to automatically generate a hasMany relation.

    initialize()方法在请求期间仅被调用一次。 在这种方法中,Phalcon将自动生成hasMany关系。

public function initialize(){
            $this->belongsTo('usersId', 'Users', 'id', array(
                'alias' => 'user'
            ));
        }

The first parameter indicates the field of the local model EmailConfirmations in the relationship; the second indicates the name of the referenced model (Users) and the third the field name in the referenced model. The alias is there to create an alternative name for the connection between these two models, so we can reference an email confirmation's user just by calling $emailConfirmationInstance->user.

第一个参数指示关系中本地模型EmailConfirmations的字段; 第二个指示参考模型的名称(用户),第三个指示参考模型中的字段名称。 alias可以为这两个模型之间的连接创建一个替代名称,因此我们只需调用$emailConfirmationInstance->user即可引用电子邮件确认的$emailConfirmationInstance->user

  1. The afterCreate() method sends a confirmation email to a user after account creation. Notice we're using abstracted functionality to send the email – the email service resides in our dependency injector and does this separately from the model itself.

    afterCreate()方法在创建帐户后向用户发送确认电子邮件。 注意,我们正在使用抽象功能发送电子邮件-电子邮件服务驻留在我们的依赖注入器中,并且与模型本身分开进行。

public function afterCreate(){
                $this->getDI()->getMail()->send(
                    array($this->user->email => $this->user->username),
                    'Please confirm your email',
                    'confirmation',
                    array( 'confirmUrl' => '/confirm/' . $this->code.'/'. $this->user->email)
                );
            }

afterCreate() and beforeValidationOnUpdate() are Events – see the docs for more information on those.

afterCreate()beforeValidationOnUpdate()是事件-有关更多信息,请参阅文档。

步骤6:控制器和库 (Step 6: Controller and Library)

The following code presents a very simple Controller skeleton and I’ll explain what view() and create() actions should look like, the rest of the code is available in the source.

下面的代码展示了一个非常简单的Controller框架,我将解释view()create()操作的外观,其余代码可在源代码中找到。

class SessionController extends ControllerBase{
            public function indexAction() {}
            public function signupAction(){}
            public function loginAction() {}
            public function confirmEmailAction(){}
    }

The signupAction() is receiving data from the form and storing it the table, while confirmEmailAction() confirms the account after signup. You can see the full file at SessionController.php.

signupAction()从表单接收数据并将其存储在表中,而confirmEmailAction()在注册后确认帐户。 您可以在SessionController.php看到完整的文件。

This part of the application is implemented in the “Mail” component.

应用程序的这一部分在“邮件”组件中实现

require_once __DIR__ . '/../../vendor/Swift/swift_required.php';
        class Mail extends Phalcon\Mvc\User\Component
        {

            protected $_transport;

            public function getTemplate($name, $params){}
            public function send($to, $subject, $name, $params){}  
        }

Here, I'm using the Swift mail library. Install it via composer, or just include it in the vendor folder like on the linked GitHub repo (see here). This class extends the Phalcon\Mvc\User\Component, which, while not required, helps us fetch it via the DI container. Now, we register this class in the services container:

在这里,我正在使用Swift邮件库。 通过composer进行安装,或仅将其包括在供应商文件夹中,如链接的GitHub存储库上一样(请参见此处 )。 此类扩展了Phalcon\Mvc\User\Component ,虽然不是必需的,但可以帮助我们通过DI容器获取它。 现在,我们在服务容器中注册该类:

<?php
        //app/config/service.php
        //Mail service uses Gmail;
        $di->set('mail', function(){
                return new Mail();
        });

The function getTemplate defines the template to be used with the email (see source for details).

函数getTemplate定义要与电子邮件一起使用的模板(有关详细信息,请参阅源代码)。

public function send($to, $subject, $name, $params)
    {
        //Settings
        $mailSettings = $this->config->mail;
        $template = $this->getTemplate($name, $params);
        // Create the message
        $message = Swift_Message::newInstance()
              ->setSubject($subject)
                              ->setTo($to)
              ->setFrom(array(
                  $mailSettings->fromEmail => $mailSettings->fromName
              ))
              ->setBody($template, 'text/html');
              if (!$this->_transport) {
                $this->_transport = Swift_SmtpTransport::newInstance(
                    $mailSettings->smtp->server,
                    $mailSettings->smtp->port,
                    $mailSettings->smtp->security
                )
                  ->setUsername($mailSettings->smtp->username)
                  ->setPassword($mailSettings->smtp->password);
              }
              // Create the Mailer using your created Transport
            $mailer = Swift_Mailer::newInstance($this->_transport);
            return $mailer->send($message);
        }

步骤7:查看 (Step 7: view)

I use scaffolding based on Twitter Bootstrap library. Even though scaffolding is a temporary solution it doesn’t mean it can’t look nice!

我使用基于Twitter Bootstrap库的脚手架 。 尽管脚手架是一个临时解决方案,但这并不意味着它看起来不太好!

Keep in mind that when using scaffolding with bootstrap, Phalcon will only generate HTML tags with appropriate HTML classes – it is up to you to include the static resources like images and CSS, so navigate to your project root and edit the file app\views\index.volt by adding the stylesheet line:

请记住,将脚手架与引导程序一起使用时,Phalcon将仅生成具有适当HTML类HTML标签-包括图像和CSS之类的静态资源取决于您,因此请导航至项目根目录并编辑文件app \ views \通过添加样式表行来index.volt

<head>
        <title>Phalcon PHP Framework</title>
        {{stylesheet_link ('http//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css',false)}} 
        {{stylesheet_link ('css/css.css')}} 
        </head>
        <body>
            {{ content() }}
        </body>

This particular example uses the Volt templating engine. Volt is an ultra-fast and designer friendly templating language written in C for PHP. It provides you with a set of helpers to write views in an easy way. More information is available in the official docs.

此特定示例使用Volt模板引擎。 Volt是一种用C语言编写的面向PHP的超快速且设计友好的模板语言。 它为您提供了一组帮助程序,可以轻松地编写视图。 官方文档中提供了更多信息。

Next, create a signup form. A typical view would incorporate usage of the Phalcon\Tag component, a convienient helper class that aids creation of forms, links and other html elements:

接下来,创建一个注册表单。 一个典型的视图将结合使用Phalcon\Tag组件,这是一个方便的帮助器类,可帮助创建表单,链接和其他html元素:

form signup

Time to try it out. Open your web brower, visit the app, and go to [app url]/signup.

是时候尝试一下了。 打开您的网络浏览器,访问该应用,然后转到[应用网址] /注册。

signup form

… and then check that user’s email account to verify that the email was sent successfully:

…,然后检查该用户的电子邮件帐户以验证电子邮件是否已成功发送:

confirm account

Perfect! Our email was sent! Click confirm to activate the account, and that's it!

完善! 我们的电子邮件已发送! 单击确认激活帐户,仅此而已!

结论 (Conclusion)

And that’s all there is to sending email messages with Phalcon and Gmail. You can of course customize your email messages as much as you’d like to make the mail more appealing.

这就是通过Phalcon和Gmail发送电子邮件的全部内容。 当然,您可以根据自己的喜好自定义电子邮件,以使邮件更具吸引力。

For more information on Phalcon check out the online documentation. Thanks for reading – leave your feedback and comments below.

有关Phalcon的更多信息,请查看在线文档 。 感谢您的阅读-在下面留下您的反馈和评论。

翻译自: https://www.sitepoint.com/sending-confirmation-emails-phalcon-swift/

phalcon和yaf

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值