A
A
Andrey Ryazantsev2020-03-15 21:17:19
symfony
Andrey Ryazantsev, 2020-03-15 21:17:19

How to call a service object and pass an object of some class in the parameters?

There is an App\Service\Status service. It needs an App\Entity\Stage class object as an argument when called. In the controller, I, not knowing how to do otherwise, call the service like this: Although we know that services in Symfony need to be called something like this: Why can't I directly create a service object, I don't understand. But the main thing is how, with the right way, to pass an object of the class App\Entity\Stage as a parameter? And a very difficult question - how to avoid passing a registered user as the second parameter?
$objStatus = new Status($stage, $this->getUser());
$objStatus = $this->get('status');

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor, 2020-03-16
@IgorPI

$objStatus = new Status($stage, $this->getUser());
This is not a service, but some kind of crap.
Services are written in the service configuration and instructions for starting them are written there.
That way

D
Dmitry Kim, 2020-03-16
@kimono

Firstly, by default, in the project settings, the Entity folder is excluded from monitoring for the presence of the necessary services. This is described in the config here:

# services.yaml
App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

Secondly, why make a service out of Entity? Entity is just a "representation of entities". Perhaps you should pass the StageRepository to the Status service. This can be done like this:
class Status {
    private $stageRepository;
    public function __construct(StageRepository $stageRepository){
        $this->stageRepository = $stageRepository;
    }
}

class SiteControllers extends AbstractController {
    public function status(Status $status) {
        // ...
    }
}

As a result, you will have access to the Status service in the controller action, and inside this service you will have access to the StageRepository.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question