If you followed Vegas CMF module schema Service Manager will allow you to load services from your modules without building service providers for any of them. They would be loaded "on the fly". Of course they can be shared and reused.
Take a look of the code below with example Bar service in Foo module:
namespace Foo\Services;
use Phalcon\DI\InjectionAwareInterface;
use Vegas\DI\InjectionAwareTrait;
class Bar implements InjectionAwareInterface
{
use InjectionAwareTrait;
public function baz()
{
// do something
}
}
Usage in controller:
$this->serviceManager->getService('foo:bar')->baz();
Usage in class with injected DI:
$this->getDI()->get('serviceManager')->getService('foo:bar')->baz();
Usage in volt template:
{{ serviceManager.getService('foo:bar').baz() }}
Sometimes you may want to use part of business logic along with rendering small template and include the whole
thing in several places through the application. In situation like this component services
can be useful. Extending typical service with \Vegas\DI\Service\ComponentAbstract
class will give
you additional render([$params])
method. Optional $params
array will be passed to
setUp
method.
namespace Foo\Services;
/**
* Class SuperBar
* @package Foo\Services
*/
class SuperBar extends \Vegas\DI\Service\ComponentAbstract
{
protected function setUp($params = array())
{
// do something with params
if (empty($params['data']) {
$params['data'] = 'foobar';
}
return array('data' => $params['data']);
}
}
Template for SuperBar service should be placed in app/modules/Foo/views/services/superBar.volt
.
Code may look like:
This is data: {{ data }}
In volt templates you can render this service using code below:
{{ serviceManager.getService('foo:superBar').render() }}