1

我想更深入地了解有关使用静态方法的知识。我正在为我的应用程序使用 laravel 5.2 框架。

在我的应用程序中,我主要使用静态函数例如,我有模型类名称,如 post,方法名称是 get_post(),只有当我错过 laravel 中的静态关键字时,它才声明为静态,它会引发错误

class Post extends Eloquent(){

    public static function get_post(){
        return DB::table('post')->get();
    }
 }

在我的控制器中,我将调用此方法

Post::get_post()

我怎样才能避免将此方法称为静态方法?根据PHPMD 1.4.0 规则

请任何人解释清楚。

4

1 回答 1

1

Laravel's Eloquent is called via the static method, so I'm not sure how to avoid this. By the way, instead of the functions you wrote, you can of course write

Post::all();

Another abstraction possibility is to use the Repository Pattern, where the Controller doesn't call the Model's functions directly, but rather something like

$activePosts = $postRepository->getActiveAndApproved();

where the $postRepository would do some of the heavy lifting on Laravel's Eloquent model doing e.g. ->where('something', true) and stuff like that - Symfony has this already a bit stronger included in their framework.

See https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/ for more detailed instructions.

Seeing also that Laravel uses Facades a lot, which is a simplified way to access functions in the service container (e.g. see config/app.php or https://laravel.com/docs/5.2/facades for more infos), it might be difficult to avoid static function calls.

于 2016-05-24T09:20:42.620 回答