locnguyen
locnguyen

Reputation: 841

Laravel How to DRY Up This Code?

I have the following code in multiple files. I would like to DRY it up.

The purpose of the code is to return the value of the current week which can be 1 to 17.

model Schedule.php

public function scopeCurrentWeekGames($query) {

    return $query->where('week', '=', $this->currentWeek());
}

public function currentWeek()
{
    $currentWeek = Schedule::distinct()
                        ->where('gameTime', '<', Carbon::now()->addHours(50))
                        ->orderBy('gameTime', 'desc')
                        ->lists('week')
                        ->first();

    return $currentWeek;
}

model Pick.php

public function scopeCurrentWeekPicks($query) {

    $currentWeek = Schedule::distinct()
                        ->where('gameTime', '<', Carbon::now()->addHours(50))
                        ->orderBy('gameTime', 'desc')
                        ->lists('week')
                        ->first();

    return $query->where('week', '=', $currentWeek);
}

controller PicksController.php

    $currentWeek = Schedule::distinct()
                        ->where('gameTime', '<', Carbon::now()->addHours(50))
                        ->orderBy('gameTime', 'desc')
                        ->lists('week')
                        ->first();

Upvotes: 1

Views: 1688

Answers (2)

Moppo
Moppo

Reputation: 19275

In Laravel, it's a good practice to make an abstraction layer over the DB using a Repository:

class ScheduleRepository 
{

    public function getCurrentWeek()
    {
        $currentWeek = Schedule::distinct()
                       ->where('gameTime', '<', Carbon::now()->addHours(50))
                       ->orderBy('gameTime', 'desc')
                       ->lists('week')
                       ->first();

        return $query->where('week', '=', $currentWeek);
    }

    /* 
    Here other methods to access the Schedule model, i.e:   
    public function getAll()
    {
        //return all schedule models...
    } 
    */

}

Then, for example in your controller:

class PicksController extends Controller {

    protected $schedule;

    //inject your repository where you need it
    public function __construct( ScheduleRepository $schedule )
    {
        $this->schedule= $schedule;
    }

    public function index()
    {
        //call a method on the repository
        $week = $this->schedule->getCurrentWeek();

        //do whathever you want with week...
    }

}

Using this approach you can keep your code DRY, because you write your queries only in your repository class, and you can access them everywhere by calling the repository methods

You can also consider to make your repository implement an interface, and you'll gain flexibility, because in future you could use another implementation of the repository (for example to access a mongodb database ) but you'll not have to change your method calls in your application

Upvotes: 3

Viktor
Viktor

Reputation: 827

I think, you can use PHP traits for this, or even better, create Helper class, and use your code from there.

For example, I'm using Laravel 4.2 and my Helper.php stored in app/libraries/:

<?php

namespace App\Libraries;

class Helper
{
    /**
     * @param $string
     *
     * @return mixed
     */
    public static function stringToBool($string)
    {
        return filter_var($string, FILTER_VALIDATE_BOOLEAN);
    }
}

And don't forget to put app/libraries to composer.json, classmap

section:
    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/services",
            "app/models",
            "app/parsers",
            "app/libraries", // Check if isset or add.
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
    },

For Laravel 5.1:

  1. Within your app/Http directory, create a helpers.php file and add your functions.
  2. Within composer.json, in the autoload block, add "files": ["app/Http/helpers.php"].
  3. Run composer dump-autoload.

You can read more info here.

Good luck!

Upvotes: 0

Related Questions