Answer the question
In order to leave comments, you need to log in
What is the best way to design a class?
Greetings. I am working on projects in Laravel. I have a helper class that does some work with the data and also works with the database (using the ORM model). Now I have implemented a helper class like this:
Helper class:
class MyHelperClass
{
private $model;
private $data;
/**
* @param $data
* @param SpecificModel $model
*/
public function __construct($data, SpecificModel $model)
{
$this->model = $model;
$this->data = $data;
}
public function doWork()
{
$concreteModel = $this->model->find(123);
$concreteModel2 = $this->model->find(456);
// какой то код, работающий с моделью...
$concreteModel->save();
$concreteModel2->delete();
}
}
// SpecificModel - ORM модель
$helper = new MyHelperClass([1, 2, 3, 4], new SpecificModel());
$helper->doWork();
Answer the question
In order to leave comments, you need to log in
Creating a service (helper) directly is not the best approach, inject it into an action method. DI will create the helper itself and inject the SpecificModel into it, and you will be able to mock it during testing.
class FooController {
public function getIndex(\MyHelperClass $helper) {
$helper->doWork([1, 2, 3, 4]);
}
}
yes, the normal approach from the SOLID principle (in your case, the dependency inversion principle D). when you test MyHelperClass you will create the tested object as isolated as possible from other classes
$this->object = new MyHelperClass([1, 2, 3, 4], $mosk);
the $mosk object will return a prepared result
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question