How to create service or helper in symfony


Posted on 14 Nov 17 by Vickey

By using service we can put our code in a class and  by service container we can use them our controllers

Create a new service class

namespace Helpers; 
use Doctrine\ORM\EntityManager; 
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; 
use Symfony\Component\HttpFoundation\RequestStack; 
class MyService 
	protected $em, $req; 
    private $path = null; 
	public function __construct(EntityManager $em, RequestStack $rs) 
        $this->em = $em; 
        $this->req = $rs; 
	public function myserviceMethod() 
        $messages = 'This is my first service'; 
        return $messages; 

Register Services  in services.yml file

        class: Helpers\MyService 
            - "@doctrine.orm.entity_manager" 
            - "@request_stack" 

Use service in controller

echo $msg = $this->get('helpers.myService')->myserviceMethod(); 


If this post help you reduce time to develop, you can help me to maintain this website :)