PHP Type Hinting Implementation of Abstract Method - Repository Pattern PHP Type Hinting Implementation of Abstract Method - Repository Pattern laravel laravel

PHP Type Hinting Implementation of Abstract Method - Repository Pattern


I was unable to find a solution to get proper type hinting with model and repositories in the context I posted this question originally.


Compromised Solution

After further studying of repository and mvc php patterns I came to the conclusion to use more specific and detailed repository functions.


The Wrong Way

For example, I was using repository base functions inside my controllers/logic classes like this:

$users =    $userRepository->where('created_at', '<', '2016-01-18 19:21:20')->where(            'permission_level',            'admin'        )->orderBy('created_at')->get('id');$posts =    $postRepository->where('posted_on', '<', '2016-01-18 19:21:20')        ->where('content', '!=', 'null')        ->chunk(            function ($posts) {                // do things            }        );

The Right Way

Now I code separate database logic functions for all my needs inside the specific repositories, so my core classes/controllers end up looking like this:

$users = $userRepository->getAdminIdsCreatedBeforeDate('2016-01-18 19:21:20');$posts = $postRepository->chunkFilledPostsBeforeDate('2016-01-18 19:21:20', function() {});

This way all the database logic is moved to the specific repository and I can type hint it's returned models. This methodology also results in cleaner easier to read code and further separates your core logic from Eloquent.


You can use the abstract keyword to offload the implementation of a method.

abstract class Model {    abstract public function find($id);}

which forces any object extending Model to implement that function.

I hope that makes sense.