P
P
plata2015-07-15 11:16:30
PHP
plata, 2015-07-15 11:16:30

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();
    }
}

Somewhere in the code:
// SpecificModel - ORM модель
$helper = new MyHelperClass([1, 2, 3, 4], new SpecificModel());
$helper->doWork();

Is this the right approach? Or is it possible to create an object directly in the helper without passing it as a constructor argument?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2018-11-22
@PHPjedi

json_decode

V
Vyacheslav Plisko, 2015-07-15
@AmdY

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]);
    }
}

D
dmitry, 2015-07-15
@dmitriylanets

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 question

Ask a Question

731 491 924 answers to any question