Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

passing parameter to controller constructor not working

I am trying to pass class object to controller constructor but its not working.

    <?php
        $di->get('UsersController', [
        new \Phalcon\Repositories\UsersRepository()
    ]);

    class UsersController extends AbstractController
    {
      /**
       * @var Phalcon\Repositories\UsersRepository
       */
      private $usersRepository;

      /**
       * @param $usersRepository
       */
      public function __construct($usersRepository)
      {
          $this->usersRepository = $usersRepository;
      }

      public function registerAction($user)
      {
          $this->usersRepository->create($user);
      }

      public function listusersAction()
      {
          var_dump($this->usersRepository->findById(1));exit;
      }
    }


    class UsersRepository implements UsersRepositoryService
    {
        /**
         * @var Users
         */
        private $users;

        public function __construct()
        {
            $this->users = new Users();
        }

        public function create(array $user)
        {
            $this->users->save($user);
        }

        public function find()
        {

        }

        public function findById($id)
        {
            return Users::findFirst($id);
        }

        public function findByEmail($email)
        {

        }

        public function updateById($id)
        {

        }

    }

when I am trying to access listusers (http://localhost:8888/cart/users/listusers) function its gives error

Warning: Missing argument 1 for UsersController::__construct() in /Applications/MAMP/htdocs/cart/app/controllers/UsersController.php on line 19

Notice: Undefined variable: usersRepository in /Applications/MAMP/htdocs/cart/app/controllers/UsersController.php on line 21

Fatal error: Call to a member function findById() on null in /Applications/MAMP/htdocs/cart/app/controllers/UsersController.php on line 31

but If I do dump usersRepository in constructor its returning object but I dont know why phalcon is calling methods directly without calling constructor or may be its calling more than two times.



7.3k
Accepted
answer
edited Mar '15

Fixed the problem by DI set method.

```php <?php

$di->set('usersRepository', array(
    'className' => 'Phalcon\Repositories\UsersRepository'
));

$di->set('UsersController', array(
    'className' => 'UsersController',
    'arguments' => array(
        array('type' => 'service', 'name' => 'usersRepository')
    )
));