我在多个文件中有以下代码。我想把它干掉。
代码的目的是返回当前周的值,可以是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;
}
模型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();
答案 0 :(得分:3)
在Laravel中,使用存储库在数据库上创建抽象层是一个很好的做法:
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数据库),但您不必更改您的方法在您的应用程序中调用
答案 1 :(得分:0)
我认为,您可以使用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:
您可以阅读更多信息here。
祝你好运!