Writing Maintainable Code using SOLID Design Principles Explained in Laravel(Single Responsibility Principle)

Writing Maintainable Code using SOLID Design Principles Explained in Laravel(Single Responsibility Principle)

Coding is fun unless you have to work with others code. Regardless of what we consider to be great code, it always demands one simple quality and that is the code must be maintainable. Proper indentation, neat and understandable variable names mean proper naming convention, cover 100% testing, proper comment about the functionality of any function or method and so on that only take your code a great code.?Any code which is not maintainable and cannot adapt to changing requirements ease is code just waiting to become static or obsolete. This blog is something that is talking about the first object-oriented design principle name the single responsibility principle which makes your code more maintainable and makes your controller more simple and clean.

You probably have heard about SOLID principles: single responsibility, open-closed, Liskov substitution, interface segregation and dependency inversion. The first letter, S, represents the Single Responsibility Principle (SRP) and its importance cannot be overstated.

According to the official definition of the Single-responsibility principle

A class should have one and only one reason to change.

Single-responsibility Principle (SRP) states that a class should have one and only one reason to change, meaning that a class should have only one job. It is one of the basic principles most developers apply to build robust and maintainable software. You only apply it to classes, but also software components and microservice.

Let's assume that you have a store method for save the locations and an update method for update the location. So both in the functions, you have some validation with the required field and if they are given then you will permit the user to submit the form.

public function store(Request $request)
{
    </code> $validator= $request->validate([
            'name' => 'required',
            'status' => 'required',
            'code' => 'required',

        ]);
if ($validator->fails()) {
            Session::flash('error', $validator->messages()->first());
            return redirect()->back();
      }
       
      
       Location::create([
           'name' => $request->name,
           'status' => $request->status,
           'code' => $request->code,
       ]);
        
       return redirect()->route('list')->with('success','Location stored Successfully');

}        

You all are familiar with this pattern. But if you look carefully you will do the same validation in the update function and check the same validation condition. This makes the controller heavy and noisy. If after some days later the new requirement comes and you will have to change in both functions which takes time and create a chance to do mistakes.

The same thing you can you a single function that is the response for this validation. Just create a FormRequest class by PHP artisan make: request LocationValidationRequest . which will create a Laravel form validator. Here just you need to add the validation attributes in rules and can make a dynamic message and change authorize false to true. and call this call to your form and it will auto validate your form and you do not need to check any validation.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class LocationValidationRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
            'status' => 'required',
            'code' =>'required'
        ];
    }
    public function messages()
    {
        return [
            'name.required' => 'Location name is required!',
            'status.required' => 'Select an status',
             'code.required' =>'Code is required'


     
        ];
    }
}
        

I just add the class in the controller method LocationValidationRequest and add use App\ Http\Requests \Location ValidationRequest at the top of the class. I need not write the same validation rule for update and store just call the class name it will auto validate the form.

public function store(LocationValidationRequest $request)
{
    
       Location::create([
           'name' => $request->name,
           'status' => $request->status,
           'code' => $request->code,
       ]);
        
       return redirect()->route('list')->with('success','Location stored Successfully');

}        

That satisfies the single-responsibility principle. This way you will rarely change controller code. Other components such as views request objects and services can still change as they are linked to business requirements, but not controllers. This is what SRP is about, and there are many techniques for writing code that meets this principle.?

blog:https://wordpress.com/post/dipghosh.home.blog/66

要查看或添加评论,请登录

社区洞察

其他会员也浏览了