【问题标题】:Laravel How to DRY Up This Code?Laravel 如何干掉这段代码?
【发布时间】:2015-10-12 23:50:18
【问题描述】:

我在多个文件中有以下代码。我想把它晒干。

代码的目的是返回当前周的值,可以是 1 到 17。

模型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);
}

控制器 PicksController.php

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

【问题讨论】:

    标签: php laravel laravel-5 dry laravel-5.1


    【解决方案1】:

    在 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...
        } 
        */
    
    }
    

    然后,例如在您的控制器中:

    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...
        }
    
    }
    

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

    您还可以考虑让您的存储库实现一个接口,您将获得灵活性,因为将来您可以使用存储库的另一个实现(例如访问 mongodb 数据库)但您不必更改您的应用程序中的方法调用

    【讨论】:

    • 如果需要来自多个存储库的数据怎么办?
    【解决方案2】:

    我认为,您可以为此使用 PHP 特征,甚至更好的是,创建 Helper 类,并从那里使用您的代码。

    例如,我使用的是 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);
        }
    }
    

    别忘了把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"
            ]
        },
    

    对于 Laravel 5.1:

    1. 在您的 app/Http 目录中,创建一个 helpers.php 文件并添加您的函数。
    2. 在composer.json的自动加载块中,添加“files”:[“app/Http/helpers.php”]。
    3. 运行 composer dump-autoload。

    您可以阅读更多信息here

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      相关资源
      最近更新 更多