我正在尝试在Silex中使用特征来获取Swift邮件程序。
我已经包括:
use Silex\Application\SwiftmailerTrait;
我还检查了traits文件是否在正确的Silex供应商目录中。
测试特征:
$app->mail(\Swift_Message::newInstance()
->setSubject("title")
->setFrom(["www.domain.com"]])
->setTo(["something@domain.com"])
->setReplyTo(["user.email@some.com"])
->setBody("TEST MESSAGE")
);
然后,我收到此错误消息:
致命错误:调用未定义的方法Silex \ Application :: mail() 第88行的... \ app.php
只是说清楚。我可以毫无问题地使用在Silex中使用swift的标准方法,它可以正常工作。
这是没有特征的工作位:
// $message = \Swift_Message::newInstance()
// ->setSubject('[YourSite] Feedback')
// ->setFrom(array('noreply@yoursite.com'))
// ->setTo(array('feedback@yoursite.com'))
// ->setBody($request->get('message'));
// $app['mailer']->send($message);
然而,我想知道究竟是什么阻止了Silex迅速运行特征。有什么想法吗?
我正在使用 PHP版本5.6.11 我的作曲家档案:
{
"require": {
"components/jquery": "^2.2",
"components/css-reset": "^2.5",
"silex/silex": "~1.2",
"symfony/browser-kit": "~2.3",
"symfony/console": "~2.3",
"symfony/config": "~2.3",
"symfony/css-selector": "~2.3",
"symfony/dom-crawler": "~2.3",
"symfony/filesystem": "~2.3",
"symfony/finder": "~2.3",
"symfony/form": "~2.3",
"symfony/locale": "~2.3",
"symfony/process": "~2.3",
"symfony/security": "~2.3",
"symfony/serializer": "~2.3",
"symfony/translation": "~2.3",
"symfony/validator": "~2.3",
"symfony/monolog-bridge": "~2.3",
"symfony/twig-bridge": "~2.3",
"doctrine/dbal": ">=2.2.0,<2.4.0-dev",
"swiftmailer/swiftmailer": "5.*",
"twig/twig": "^1.24",
"symfony/security-csrf": "~2.3",
"symfony/yaml": "~2.3"
},
"autoload": {
"psr-4": {
"WL\\Form\\": "WL/Form/",
"WL\\Email\\": "WL/Email/"
},
"classmap":[],
"files":[]
}
}
答案 0 :(得分:2)
您需要创建一个自定义Application
类,该类扩展\Silex\Application
并使用该特征。
假设基础项目树为:
project/
|
|_app/
|
|_src/
|
|_vendor/
|
|_web/
您需要一个类定义:
// src/WL/App.php
namespace WL;
class App extends \Silex\Application
{
use \Silex\Application\SwiftmailerTrait;
// add some other trait
// even custom methods or traits
}
引导程序:
// app/bootstrap.php
$app = new \WL\App();
// configure it, register controllers and services, ...
// or import them
foreach (glob(__DIR__ . "/../src/WL/Controller/*.php") as $controllers_provider) {
include_once $controllers_provider;
}
return $app;
所以你可以导入一个控制器集合,如:
// src/Wl/Controller/blog.php
use Symfony\Component\HttpFoundation\Request;
/** @var \Silex\ControllerCollection $blog */
$blog = $app['controllers_factory'];
// define some routes
$blog->post('/send-mail', function (Request $request, \WL\App $app)
{
// Now this application passed to your controller is an
// instance of custom \App which has the trait you want
// in contrary with the default \Silex\Application
$app->mail(...
}
$app->mount('/blog', $blog);
前控制器:
// web/index.php
// define autoloading
// customize debug and server parameters
$app = require_once '../app/bootstrap.php';
$app->run();