D
D
Daria Motorina2020-07-20 17:31:25
PHP
Daria Motorina, 2020-07-20 17:31:25

How to abstract constructor argument with this approach?

I came across a situation where I want to avoid shitty code, but I don’t know how.

There is a Laravel JSON API package, there is its documentation. There are adapter classes that communicate with application models. The constructor specifies pagination strategies and model classes. Due to the fact that model classes are set by instantiation inside the constructor, I cannot move the constructor method to an abstract class so that pagination is the same everywhere. I can’t write this in an abstract class, because Laravel’s Model is also an abstract class.

public function __construct(CursorStrategy $paging)
 {
        parent::__construct(new Model(), $paging);
 }

Is there a way to refactor this?

Documentation : Cursor-Based Pagination Code

example from the documentation that demonstrates the problem:
namespace App\JsonApi\Comments;

use App\Comment;
use CloudCreativity\LaravelJsonApi\Pagination\CursorStrategy;
use CloudCreativity\LaravelJsonApi\Eloquent\AbstractAdapter;

class Adapter extends AbstractAdapter
{

    /**
     * @param CursorStrategy $paging
     */
    public function __construct(CursorStrategy $paging)
    {
        parent::__construct(new Post(), $paging);
    }

    // ...
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
BoShurik, 2020-07-20
@glaphire

If I understand correctly, then

abstract class AbstractAdapter extends \CloudCreativity\LaravelJsonApi\Eloquent\AbstractAdapter
{
    public function __construct(CursorStrategy $paging)
    {
        parent::__construct($this->getModelInstance(), $paging);
    }

    abstract protected function getModelInstance();

    // ...
}

M
Maxim, 2020-07-20
@myks92

Of course, I'm not very familiar with Laravel, but I don't really like inheritance. It's better to use DI. Therefore, in order not to inherit from framework classes, just don't inherit from them) It's that simple) Create your own classes and connect Laravel to them already. Then the framework independence will increase. And configure the implementation through DI. Adapters can have a support method that checks if the adapter is supported.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question