php - How to create a new injectable service in Phalcon -



php - How to create a new injectable service in Phalcon -

i'm trying build basic "json getter" phalcon-based webapp, that:

function getjson($url, $assoc=false) { $curl = curl_init($url); $json = curl_exec($curl); curl_close($curl); homecoming json_decode($json, $assoc); }

and of course of study create stuff globally available, perchance injectable service. best way that? should implement phalcon\di\injectable? , then, how can include new class , feed di?

thanks!

you extend phalcon\di\injectable don't have to. service can represented class. docs pretty explain how work dependency injection in general , phalcon.

class jsonservice { public function getjson($url, $assoc=false) { $curl = curl_init($url); $json = curl_exec($curl); curl_close($curl); homecoming json_decode($json, $assoc); } } $di = new phalcon\di(); //register "db" service in container $di->setshared('db', function() { homecoming new connection(array( "host" => "localhost", "username" => "root", "password" => "secret", "dbname" => "invo" )); }); //register "filter" service in container $di->setshared('filter', function() { homecoming new filter(); }); // json service... $di->setshared('jsonservice', function() { homecoming new jsonservice(); }); // later in app... di::getdefault()->getshared('jsonservice')->getjson(…); // or if class you're accessing di extends `phalcon\di\injectable` $this->di->getshared('jsonservice')->getjson(…);

just pay attending get / set vs. getshared / setshared, there services may cause problems if created multiple times on , on 1 time again (not shared), e.g., take lot of resources when instantiated. setting service shared ensures it's created 1 time , instance reused there after.

php dependency-injection phalcon

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -