• Developer New

    Tuesday, March 14, 2017

    HOW TO DO BEST CODING PRACTICES IN LARAVEL

    The topics that will be discussed in this Article are as follows:
    • Basic and advanced practices
    • Real-life examples of design patterns used in Laravel
    • The reasons why these design patterns are used in the examples

    BASIC PRACTICES

    As a developer, when you are working on an application, there should be a systematic order to things to prevent confusion and allow flexibility. For example, in an MVC architecture, Controller should only hold the logic and Model should only hold dataflow-related stuff. You should not write database queries in View files. This way, anyone working on the project can find what they are looking for easily and can change, fork, or improve it with greater ease. If this is not followed, the project will turn into a mess as it gets bigger and bigger.
    A basic good practice would be to avoid repeating yourself. If you’re using a code snippet or a condition a number of times, it’d be better for you to prepare a method or a scope for that action. This way, you wouldn’t have to repeat yourself over and over. For example, let’s say we have an imaginary Controller as follows:

    <?php
    
    class UserController extends BaseController {
    
       //An imaginary method that lists all active users
       public function listUsers() {
    
          $users = User::where('active', 1)->get();
    
          return View::make('frontend.users.list')
             ->with('users', $users);
       }
    
    
       //An imaginary method that finds a specific user
       public function fetch($id) {
    
          $user = User::where('active', 1)->find($id);
    
           return View::make('frontend.users.single')
             ->with('user', $user);
    
       }
    
    }
    As you can see, the where() condition checks if active is repeated twice. In real-world examples, it would be used even more.
    To prevent this, in Laravel, you can use query scopes. Query scopes are single functions that help you reuse the logic in Models. Let’s define a query scope in Model and change the Controller method as follows:
    <?php
    
    //Model File
    Class User extends Eloquent {
    
       //We've defined a Query scope called active
       public function scopeActive($query) {
          return $query->where('active', 1);
       }
    
    }
    
    
    
    
    //Controller File
    class UserController extends BaseController {
    
       //An imaginary method that lists all active users
       public function listUsers() {
    
          $users = User::active()->get();
    
          return View::make('frontend.users.list')
             ->with('users', $users);
       }
    
    
       //An imaginary method that finds a specific user
       public function fetch($id) {
    
          $user = User::active()->find($id);
    
          return View::make('frontend.users.single')
             ->with('user', $user);
    
       }
    
    }
    As you can see, we’ve defined a method called scopeActive() in Model, which is prefixed with the word scope and CamelCased. This way, Laravel can understand that it’s a query scope, and you can use that scope directly. As you can see, the conditions in the Controller have also changed. They have changed from where('active', 1) to active().
    Design patterns are advanced practices and can be used to keep the code tidy and systematic using various approaches.

    ADVANCED PRACTICES

    In this subsection, we will see various design patterns’ usage in Laravel. If you test the custom classes that include the design patterns,, they should be autoloaded in your application. This can be done either by adding them to the ClassLoader::addDirectories()array of the global.php file (which can be found by navigating to app/start) or the start.php file in the bootstrap folder. Alternatively, we can add a psr-0 autoload in composer.json.
    To add directories from app/start/global.php, first find the following code:
    ClassLoader::addDirectories(array(
    
       app_path().'/commands',
       app_path().'/controllers',
       app_path().'/models',
       app_path().'/database/seeds',
    
    ));
    Then add your folders below. The resulting code will look as follows:
    ClassLoader::addDirectories(array(
    app_path().'/commands',
     app_path().'/controllers',
     app_path().'/models',
     app_path().'/database/seeds',
    
    //our custom directory that holds classes
     app_path().'/acme',
     ));
    
    If you want to autoload classes or files from the composer.json file using the psr-0autoload, you have to add the namespace and directory into composer.json. The key will be the namespace and the value will be the path of the folder that holds the files and classes to be autoloaded. Have a look at the following code:
    "autoload": {
    
        "psr-0": {
            "Acme": "app/lib"
        }
    }
    In this example, if our composer.json file doesn’t have a psr-0 object, first we’ll create it and then add the namespace and the path values inside. You can see we have a namespace called Acme, which is under the folder app/lib.
    If you don’t want to autoload a whole folder but only a few single files, you can also use the filesobject in composer.json. It’s a single object that only holds the paths of files.
    "autoload": {
        "files": [
            "app/acme/myFunctions.php"
        ]
    },
    After adding these values, you need to dump the autoload files and make Laravel understand them. To do this, after editing the composer.json file, simply run the following command:
    composer dump-autoload
    You can also run the following command if the composer is not installed in your environment:
    php composer.phar dump-autoload
    After this, the classes or files that you’ve just added will be autoloaded and available for your project

    No comments:

    Post a Comment

    Fashion

    Beauty

    Travel