我在Laravel 5.5中工作,我不想在控制器中编写逻辑,我想将逻辑形式的Controller分开。写一些类似于接口和服务的东西,就像我们用户在" ASP.NET MVC"框架。
答案 0 :(得分:-1)
我也从Zend转到Laravel并错过了我的服务。为了安抚自己,我已经在名称空间App \ Services中实现了一个Service命名空间。在那里,我做我所有的模型/验证handeling。我没有经历任何功能或任何损失。
<?php
namespace App\Http\Controllers;
use App\Services\Contact as ContactService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;
class IndexController extends Controller
{
/**
* Create a new controller instance.
*
* @param Request $request
* @return void
*/
public function __construct(Request $request)
{
$this->_request = $request;
}
/**
* Standard contact page
*
* @return contact page
*/
public function contact(ContactService $contactService)
{
$errors = null;
$success = false;
if ($this->_request->isMethod('post')) {
$validator = $contactService->validator($this->_request->all());
if ($validator->fails()) {
$errors = $validator->errors();
} else {
$contactService->create($validator->getData());
$success = true;
}
}
return view('pages/contact', ['errors' => $errors, 'success' => $success]);
}
}
服务示例:
<?php
namespace App\Services;
use Validator;
use Mail;
use App\Models\Contact as ContactModel;
class Contact
{
/**
* Get a validator for a contact.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
public function validator(array $data)
{
return Validator::make($data, [
'email' => 'required|email|max:255',
'phone' => 'max:255',
'firstName' => 'required|max:255',
'lastName' => 'required|max:255',
'message' => 'required'
]);
}
/**
* Create a new contact instance after a valid form.
*
* @param array $data
* @return ContactModel
*/
public function create(array $data)
{
$data = [
'email' => $data['email'],
'firstName' => $data['firstName'],
'lastName' => $data['lastName'],
'language' => $data['language'],
'phone' => $data['phone'],
'message' => $data['message']
];
// Send an email
Mail::send('emails.contact', ['data' => $data], function ($m) use ($data) {
$m->from(config('mail.from.address'), config('mail.from.name'));
$m->to(env('MAIL_TO', 'hello@world.com'), env('MAIL_TO'))->subject('Contact form entry from: ' . $data['firstName']);
});
return ContactModel::create($data);
}
}