How to create service or helper in symfony

Symfony

Posted on 14 Nov 17 by Vickey
  230



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

#src/AppBundle/Helper/MyService.php 
 
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

#src/AppBundle/Resources/config/services.yml  
helpers.myService: 
        class: Helpers\MyService 
        arguments: 
            - "@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 :)
www.000webhost.com