Dependency Injection for Custom API Action

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • philzo
    Junior Member
    • May 2024
    • 7

    Dependency Injection for Custom API Action

    Hi,

    I wrote a custom API Action, which I can trigger from the frontend. However, the `EntityManager` doesn't seem to get injected.
    Any idea what i need to change to get it to work?

    Code:
    [2024-08-21 18:31:21] WARNING: E_WARNING: Undefined variable $entityManager
    [2024-08-21 18:31:21] WARNING: E_WARNING: Undefined property: Espo\Modules\ExtLoginModule\Api\ExtLoginAction::$
    [2024-08-21 18:31:21] ERROR: Slim Application Error Type: Error Code: 0 Message: Call to a member function getEntityById() on null File:​

    Code:
    ExtLoginModule/API/ExtLoginAction.php
    PHP Code:
    <?php
    namespace Espo\Modules\ExtLoginModule\Api;
    use Espo\Core\Api\Action;
    use Espo\Core\Api\Request;
    use Espo\Core\Api\Response;
    use Espo\Core\Api\ResponseComposer;
    use Espo\Core\Exceptions\BadRequest;
    use Espo\Core\Exceptions\Error;
    use Espo\ORM\EntityManager;
    class ExtLoginAction implements Action
    {
      public function __construct(private EntityManager $entityManager)
      {}
    
      public function process(Request $request): Response
      {
        ...
        $entity = $this->$entityManager->getEntityById('User', $id);​​
      }}
  • azidevnom
    Junior Member
    • Oct 2019
    • 20

    #2
    You have an extra $ here:

    $this->$entityManager->getEntityById('User', $id);

    Should be:

    $this->entityManager->getEntityById('User', $id);

    Comment

    • philzo
      Junior Member
      • May 2024
      • 7

      #3
      Oh my. What an oversight!
      Thank you!

      Comment

      • esforim
        Active Community Member
        • Jan 2020
        • 2206

        #4
        Cool, hope you share more of your code.

        One recommendation is to use AI to try find error for you. Sometime I miss a comma, and ; and bracket ) and the AI help me see the missing symbol. I don't code, this is just Formula.

        Comment

        Working...