No announcement yet.

Calling a service method from a job class. [ESPO Upgrade 6.1.0 -> 7.0.1]

  • Filter
  • Time
  • Show
Clear All
new posts

  • Calling a service method from a job class. [ESPO Upgrade 6.1.0 -> 7.0.1]


    In ESPO 6.1.0 I had:
    protected function getRecordService($name)
    {[INDENT]if ($this->getServiceFactory()->checkExists($name)) {[/INDENT][INDENT=2]$service = $this->getServiceFactory()->create($name);[/INDENT][INDENT]} else {[/INDENT][INDENT=2]$service = $this->getServiceFactory()->create('Record');
    return $service;[/INDENT]
    public function run()
    This would call the `serviceFunctionName` function which is under the Services/ class.

    How do I achieve the same in 7.0.1 as I cannot use the getServiceFactory() method from job class anymore.

    telecastg Any ideas? Thank You :-)

  • #2
    This is the same as No need to create a topic for each class.

    Jobs, Controlles, etc.. they all are same. Inject needed classes into a constructor. It's not Espo-specific magic. It's a common principle of programming of last 2 decades.


    • #3

      Inject any class you want into the constructor.


      • yuri
        yuri commented
        Editing a comment
        I recommend to read and understand the article about dependency injection in the documentation. Almost every class is created via DI factory. The principle is the same for all them.

        There's NO such thing as SERVICES in Espo anymore. There is the record service class (Espo\Core\Record\Service) that handles API requests. It's a layer between CRUD controller and internal logics (ORM, Select framework). It's NOT RECOMMENDED to extend the Record\Service class. There should not be a need to extend it as almost any customization can be done with different extension frameworks (hooks, duplicate checkers etc). Even though there are some classes extended from the Record\Services, it's because it's a legacy and I didn't bother to remove/refactor them yet.

        This record service class does have dependency recordServiceContainer. It's already there. You can include this class Espo\Core\Record\ServiceContainer to any class (Job, Hook, you name it) and use it the same way.

      • yuri
        yuri commented
        Editing a comment
        When one wants to write some business logic, it's not needed to create/extend a service class as it was before v6. ServiceFactory is deprecated. Create just a plain PHP class in any namespace you like (Espo\Custom\*, Espo\Modules\ModuleName\*), inject all that is needed via constructor (EntityManager, Config, Metadata, etc.).

        Then your Job, Hook etc. can use this class. Inject this class via constructor.
        Last edited by yuri; 04-21-2022, 05:45 PM.

      • telecastg
        telecastg commented
        Editing a comment
        Got it, thanks so much for the explanation.