简体   繁体   English

Laravel如何干掉此代码?

[英]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. 代码的目的是返回当前周的值,可以是1到17。

model Schedule.php model.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 模特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 控制器PicksController.php

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

In Laravel, it's a good practice to make an abstraction layer over the DB using a Repository: 在Laravel中,使用Repository在DB上创建一个抽象层是一个很好的做法:

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 使用这种方法可以保持代码DRY ,因为您只在存储库类中编写查询,并且可以通过调用存储库方法在任何地方访问它们

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 您还可以考虑使您的存储库实现一个接口,并且您将获得灵活性,因为将来您可以使用存储库的另一个实现(例如访问mongodb数据库),但您不必更改方法调用在你的申请中

I think, you can use PHP traits for this, or even better, create Helper class, and use your code from there. 我认为,您可以使用PHP特性,甚至更好地创建Helper类,并使用您的代码。

For example, I'm using Laravel 4.2 and my Helper.php stored in app/libraries/ : 例如,我正在使用Laravel 4.2和我的Helper.php存储在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 并且不要忘记将app/libraries放到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: 对于Laravel 5.1:

  1. Within your app/Http directory, create a helpers.php file and add your functions. 在app / Http目录中,创建一个helpers.php文件并添加您的函数。
  2. Within composer.json, in the autoload block, add "files": ["app/Http/helpers.php"]. 在composer.json中,在自动加载块中,添加“files”:[“app / Http / helpers.php”]。
  3. Run composer dump-autoload. 运行composer dump-autoload。

You can read more info here . 您可以在这里阅读更多信息。

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM