我应该把这段代码放在Laravel的什么地方? [英] Where should I put this code in Laravel?
问题描述
我正在使用Laravel4建立一个站点.这是我的第一个Laravel项目,所以我仍在学习如何将所有东西组合在一起以及应该将它们放到哪里.
I'm building a site using Laravel4. This is my first Laravel project so I'm still learning how everything fits together and where it should all go.
我刚刚将 Laravel-Mandrill-Request 包添加到了我的网站.我可以通过如下所示的测试控制器中的方法发送电子邮件:
I just added in the Laravel-Mandrill-Request bundle to my site. I'm able to send out emails from a method in my test Controller that looks like this:
public function sendMeSomething(){
$payload = array(
'message' => array(
'subject' => 'Greetings!!',
'from_email' => 'xxxx@yyyy.com',
'to' => array(
array('email'=>'aaaa@bbbb.com'),
array('email' => 'cccc@bbbb.com')
),
'global_merge_vars' => array(
array(
'name' => 'time',
'content' => time()
),
array(
"name" => "SenderName",
"content" => "Chris"
)
),
'merge_vars' => array(
array(
'rcpt' => 'aaaa@bbbb.com',
'vars' => array(
array(
'name' => 'firstName',
'content' => 'Christopher'
)
)
),
array(
'rcpt' => 'cccc@bbbb.com',
'vars' => array(
array(
'name' => 'firstName',
'content' => 'Chris!'
)
)
)
)
),
'template_name' => "sk-hello",
'template_content' => array(
array(
'greetings' => 'why hello!'
)
)
);
$result = Mandrill::request('messages/send-template', $payload);
return "check your email. result: " . var_dump($result);
}
一切都在测试中运行良好,因此现在我准备开始将其构建到实际的站点工具中.
Everything works great in the test, so now I'm ready to start building it into my actual site tools.
我想通过构建一种动态构建有效负载变量的方法来对其进行抽象.
I would like to abstract it a bit by building a method to dynamically build the payload variable.
我的问题是,放置此代码的正确位置在哪里?似乎它不应该在它自己的控制器中,因为它是一个可以从其他控制器的不同位置调用的工具.它不是只与数据库中的表进行交互的东西,因此似乎不应该将其作为模型.我应该为其创建立面吗?这堂课应该去哪儿?
My question is, where would be the proper place to put this code? It doesn't seem like it should be in it's own controller because it's a tool that will be called from various places in other controllers. It's not something that interacts solely with a table in my database so it doesn't seem like it should be a model. Should I create a facade for it? Where should this class go?
推荐答案
创建一个服务,假设Mailer
在您的控制器或其他服务中以这种方式使用它:
Create a service, let's say Mailer
to use it this way in your controllers or other services:
Mailer::send('emails.greetings', 'Welcome!', $user->email);
您将需要:
- 您的基本服务类(Mailer.php)
- 服务提供商(MailerServiceProvider.php)
- 外观(MailerFacade.php)
看看这篇文章: http://fideloper.com/create-facade-laravel -4
您可以为服务创建文件夹,如下所示:
You can create folders for your services, like this:
app
│ └── App
│ └── Services
│ └── Mailer
│ ├── Mailer.php
│ ├── MailerServiceProvider.php
│ └── MailerFacade.php
并为其命名空间:
<?php namespace App\Services;
并使用PSR-4通过名称空间自动加载类,但将其添加到composer.json:
And use PSR-4 to autoload your classes via namespace, but adding this to your composer.json:
"autoload": {
"psr-4": {
"App\\": "app/App",
},
},
并执行
composer dumpautoload
这篇关于我应该把这段代码放在Laravel的什么地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!