Infobuscador Infobuscador - 1 month ago 8
PHP Question

Phalcon 3 RuntimeException: Trying to call method get on a non-object

I am trying to code a library with Phalcon 3 and I get an error when calling the Cookies service.

Can anyone help me please?

The error i get is:


RuntimeException: Trying to call method get on a non-object


My code is next:

loader.php

$loader->registerDirs(
[
$config->application->controllersDir,
$config->application->modelsDir,
$config->application->incubatorDir.'Mailer/',
$config->application->libraryDir.'gAuth/',
]
)->register();


Services.php

$di->setShared('cookies', function () {
$cookies = new Cookies();
$cookies->useEncryption(false);
return $cookies;
});

$di->set('gauth', function(){
$gauth = new gAuth();
return $gauth;
});


authController.php

public function authAction(){
$this->gauth->store();
}


gAuth.php

use Phalcon\Crypt;
use Phalcon\Http\Response\Cookies;


class gAuth
{
public $token;
protected $cookie;
private $secret;
private $crypt;

public function __construct()
{
$this->secret = '************;
$this->crypt = new Crypt();
$this->cookie = new Cookies();
$this->cookie->useEncryption(false);
}

public function storeToken()
{
// here I get the error: Trying to call method get on a non-object
$this->cookie->set('tkn', '***', time() + 3600, '/', null, 'web.com', null)->send();
}

Answer

You are calling $this->cookie in your controller, but in your DI you used cookies.

So you need to use $this->cookies.

Also you don't need to recreate the cookie object in your controller. What's the point of using the DI then?

Comments