Answer the question
In order to leave comments, you need to log in
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);
}
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
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();
// ...
}
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 questionAsk a Question
731 491 924 answers to any question