Skip to content

Commit

Permalink
Support Phalcon 2.0.
Browse files Browse the repository at this point in the history
- PSR-2
- Configuration improvement
  • Loading branch information
vanchelo committed Sep 7, 2015
1 parent 88645c3 commit 449e267
Show file tree
Hide file tree
Showing 6 changed files with 181 additions and 148 deletions.
60 changes: 42 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
phalcon-mailer
Phalcon Mailer
==============
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/vanchelo/phalcon-mailer/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Сервис для отправки почты для Phalcon используя Swift Mailer.
Удобная библиотека для отправки Вашей почты в [Phalcon](http://phalconphp.com/).

Код заимствован из Laravel 4 и адаптирован под Phalcon.

##Установка
C помощью `composer`:
Добавить в файл `composer.json` в секцию `require`:

Добавить в файл `composer.json` в секцию `require` следующую строку:
```
"vanchelo/phalcon-mailer": "dev-master"
```
Expand All @@ -20,7 +19,10 @@ C помощью `composer`:
}
}
```
В терминале выполнить команду `composer update`
После этого выполните в терминале команду:
```bash
composer update
```

Инициализация сервиса
---------
Expand All @@ -34,6 +36,32 @@ $this->di['mailer'] = function() {
return $service->mailer();
};
```
или с передачей параметров на этапе инициализации сервиса

```php
/**
* Register Mailer Service
*/
$this->di['mailer'] = function() {
$service = new MailerService([
'driver' => 'smtp', // mail, sendmail, smtp
'host' => 'smtp.email.com',
'port' => 587,
'from' => [
'address' => '[email protected]',
'name' => 'My Cool Company',
],
'encryption' => 'tls',
'username' => '[email protected]',
'password' => 'some-strong-password',
'sendmail' => '/usr/sbin/sendmail -bs',
// Путь используемый для поиска шаблонов писем
'viewsDir' => __DIR__ . '/../app/views/', // optional
]);

return $service->mailer();
};
```

Отправка письма
---------
Expand All @@ -55,27 +83,23 @@ $this->mailer->send('emails/xxx', [
Настройки по умолчанию необходимо прописать в конфигурационном файле вашего приложения config/config.php
```php
<?php
return new \Phalcon\Config(array(
'application' => array(
// Путь используемый для поиска шаблонов писем
'viewsDir' => __DIR__ . '/../app/views/',
/* ... */
),

'mail' => array(
return new \Phalcon\Config([
'mail' => [
'driver' => 'smtp', // mail, sendmail, smtp
'host' => 'smtp.email.com',
'port' => 587,
'from' => array(
'from' => [
'address' => '[email protected]',
'name' => 'My Cool Company'
),
],
'encryption' => 'tls',
'username' => '[email protected]',
'password' => 'some-strong-password',
'sendmail' => '/usr/sbin/sendmail -bs',
),
));
// Путь используемый для поиска шаблонов писем
'viewsDir' => __DIR__ . '/../app/views/', // optional
],
]);
```

Если будет необходимость, настройки почты можно вынести в отдельный конфигурационный файл
Expand Down
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@
"swiftmailer/swiftmailer": "~5.3",
"jeremeamia/superclosure": "~1.0.1"
},
"require-dev": {
"phalcon/devtools": "~2.0"
},
"autoload": {
"psr-4": {
"Vanchelo\\Mailer\\": "src/"
Expand Down
77 changes: 39 additions & 38 deletions src/Mailer.php
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
<?php namespace Vanchelo\Mailer;
<?php

namespace Vanchelo\Mailer;

use Closure;
use Phalcon\DiInterface;
use Swift_Mailer;
use Swift_Message;
use Jeremeamia\SuperClosure\SerializableClosure;
use Phalcon\DI\InjectionAwareInterface;
use Phalcon\Queue\Beanstalk;

/**
* Class Mailer
*
* @package Vanchelo\Mailer
*/
class Mailer implements InjectionAwareInterface
{
/**
Expand Down Expand Up @@ -45,15 +53,15 @@ class Mailer implements InjectionAwareInterface
protected $queue;

/**
* @var \Phalcon\DiInterface
* @var DiInterface
*/
protected $di;

/**
* Create a new Mailer instance
*
* @param $view
* @param Swift_Mailer $swift
* @param \Phalcon\Mvc\View $view
* @param Swift_Mailer $swift
*/
public function __construct($view, Swift_Mailer $swift)
{
Expand All @@ -76,8 +84,8 @@ public function alwaysFrom($address, $name = null)
* Send a new message when only a plain part
*
* @param string $view
* @param array $data
* @param mixed $callback
* @param array $data
* @param mixed $callback
*
* @return int
*/
Expand All @@ -89,8 +97,8 @@ public function plain($view, array $data, $callback)
/**
* Send a new message using a view
*
* @param string|array $view
* @param array $data
* @param string|array $view
* @param array $data
* @param Closure|string $callback
*
* @return int
Expand Down Expand Up @@ -120,19 +128,17 @@ public function send($view, array $data, $callback)
* Add the content to a given message
*
* @param Message $message
* @param string $view
* @param string $plain
* @param array $data
* @param string $view
* @param string $plain
* @param array $data
*/
protected function addContent($message, $view, $plain, $data)
protected function addContent(Message $message, $view, $plain, $data)
{
if (isset($view))
{
if (isset($view)) {
$message->setBody($this->render($view, $data), 'text/html');
}

if (isset($plain))
{
if (isset($plain)) {
$message->addPart($this->render($plain, $data), 'text/plain');
}
}
Expand All @@ -151,19 +157,17 @@ protected function parseView($view)
// If the given view is an array with numeric keys, we will just assume that
// both a "pretty" and "plain" view were provided, so we will return this
// array as is, since must should contain both views with numeric keys.
if (is_array($view) && isset($view[0]))
{
if (is_array($view) && isset($view[0])) {
return $view;
}

// If the view is an array, but doesn't contain numeric keys, we will assume
// the the views are being explicitly specified and will extract them via
// named keys instead, allowing the developers to use one or the other.
elseif (is_array($view))
{
elseif (is_array($view)) {
return [
array_get($view, 'html'),
array_get($view, 'text')
array_get($view, 'text'),
];
}

Expand All @@ -177,7 +181,7 @@ protected function parseView($view)
*
* @return int
*/
public function sendSwiftMessage($message)
public function sendSwiftMessage(Swift_Message $message)
{
return $this->swift->send($message);
}
Expand All @@ -193,8 +197,7 @@ public function sendSwiftMessage($message)
*/
protected function callMessageBuilder($callback, $message)
{
if ($callback instanceof Closure)
{
if ($callback instanceof Closure) {
return call_user_func($callback, $message);
}

Expand All @@ -213,8 +216,7 @@ protected function createMessage()
// If a global from address has been specified we will set it on every message
// instances so the developer does not have to repeat themselves every time
// they create a new message. We will just go ahead and push the address.
if (isset($this->from['address']))
{
if (isset($this->from['address'])) {
$message->from($this->from['address'], $this->from['name']);
}

Expand All @@ -225,7 +227,7 @@ protected function createMessage()
* Render the given view
*
* @param string $view
* @param array $data
* @param array $data
*
* @return string
*/
Expand Down Expand Up @@ -277,7 +279,7 @@ public function setSwiftMailer($swift)
*/
protected function buildQueueCallable($callback)
{
if ( ! $callback instanceof Closure) return $callback;
if (!$callback instanceof Closure) return $callback;

return serialize(new SerializableClosure($callback));
}
Expand All @@ -286,7 +288,7 @@ protected function buildQueueCallable($callback)
* Handle a queued e-mail message job
*
* @param \Phalcon\Queue\Beanstalk\Job $job
* @param array $data
* @param array $data
*/
public function handleQueuedMessage($job, $data)
{
Expand All @@ -304,8 +306,7 @@ public function handleQueuedMessage($job, $data)
*/
protected function getQueuedCallable(array $data)
{
if (str_contains($data['callback'], 'SerializableClosure'))
{
if (str_contains($data['callback'], 'SerializableClosure')) {
return with(unserialize($data['callback']))->getClosure();
}

Expand All @@ -315,8 +316,8 @@ protected function getQueuedCallable(array $data)
/**
* Queue a new e-mail message for sending
*
* @param string|array $view
* @param array $data
* @param string|array $view
* @param array $data
* @param \Closure|string $callback
*
* @return mixed
Expand All @@ -332,7 +333,7 @@ public function queue($view, array $data, $callback)
'data' => [
'view' => $view,
'data' => $data,
'callback' => $callback
'callback' => $callback,
],
]));
}
Expand All @@ -350,7 +351,7 @@ public function failures()
/**
* Set the Beanstalk queue instance
*
* @param \Phalcon\Queue\Beanstalk $queue
* @param \Phalcon\Queue\Beanstalk $queue
*
* @return self
*/
Expand All @@ -364,17 +365,17 @@ public function setQueue(Beanstalk $queue)
/**
* Sets the dependency injector
*
* @param \Phalcon\DiInterface $dependencyInjector
* @param mixed $dependencyInjector
*/
public function setDI($dependencyInjector)
public function setDI(DiInterface $dependencyInjector)
{
$this->di = $dependencyInjector;
}

/**
* Returns the internal dependency injector
*
* @return \Phalcon\DiInterface
* @return DiInterface
*/
public function getDI()
{
Expand Down
Loading

0 comments on commit 449e267

Please sign in to comment.