1

I would like to more in depth knowledge about using static methods . I'm using laravel 5.2 framework for my application.

In my application mostly i have used static functions For example i have model class name like post and method name is get_post() and its declared as static only if i missed static keyword in laravel it throws error

class Post extends Eloquent(){

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

In my controller i will call this above method

Post::get_post()

How could i avoid to call this method as static ? as per the PHPMD 1.4.0 rule

Anyone please explain clearly.

Alice
  • 25
  • 2
  • 9

1 Answers1

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.

Oliver Adria
  • 1,123
  • 11
  • 23
  • 1
    Moving the use of the static method call to a repository doesn't change the use of the facade (or static methods), it just moves it to a different place. – datashaman Jul 02 '16 at 07:36