Asked a question of simple and flexible actions in controllers. Actually using my approach to design, I ran into problems for which I want to take advantage of your advice. Examples on laravel5
Controller:
<?php namespace App\Http\Controllers; use App\Http\Requests\TestRequest; use App\Services\TestService; use Exception; use Session; use DB; class TestController extends Controller { protected $testService; public function __construct(TestService $testService) { $this->testService = $testService; } public function index(TestRequest $request) { DB::beginTransaction(); try { $result = $this->testService->process($request->all()); if ($result) { DB::commit(); // Данные сохранены успешно } else { DB::rollBack(); // Ошибка сохранения данных } } catch (Exception $e) { DB::rollBack(); // Ошибка обработки данных } //return redirect || view; } } Service
<?php namespace App\Services; use ErrorException; class TestService { public function process(array $data) { // Логика и аналитика для получания переменной $var $var = 7; if ($var > $data['count']) { throw new ErrorException('Возникла критическая ошибка, ...'); } return true; } } Rekvest
<?php namespace App\Http\Requests; use HttpResponseException; use Validator; use Response; class TestRequest extends Request { public function authorize() { return true; } public function rules() { $this->sanitize(); return [ // rules ]; } public function messages() { return []; } public function sanitize() { $input = $this->all(); $input['var1'] = filter_var(isset($input['var1']) ? $input['var1'] : null, FILTER_SANITIZE_STRING); $input['var2'] = filter_var(isset($input['var2']) ? $input['var2'] : null, FILTER_SANITIZE_STRING); $input['var3'] = filter_var(isset($input['var3']) ? $input['var3'] : null, FILTER_SANITIZE_STRING); $this->replace($input); } } There was a question / problem with data validation
I have to do a request for good validation, however, quite often there are situations in which I need to check if there is an entry in the table and immediately work with it. Ie there are 2 requests, 1 - through the framework validators, and 2 - when in the controller or service we get the same record for further work.
In addition to this, sometimes the logic can be quite intricate, so to get some data for validation, you need to do a number of logical actions. I don’t really like the idea of putting pieces of logic into a request (even if pulling services into a request) to do validation, and then almost the same thing, to continue working with this case in the service.
Accordingly, an inconvenient situation is obtained when part of the validation needs to be placed in the request, and part in the service. There is still the problem of error rendering, when we get two types of validation, request and validation by means of services exepsins.
Please tell me (preferably with examples of pseudocode) how to arrange it beautifully? I would be very grateful for the detailed answers on this issue.