facebook twitter hatena line email

Php/Symfony/Symfony2/サービス作成

提供: 初心者エンジニアの簡易メモ
2017年1月16日 (月) 11:40時点におけるAdmin (トーク | 投稿記録)による版 (ページの作成:「==サンプルサービス作成== -src/Acme/HelloBundle/Services/SampleexampleService.php namespace Acme\HelloBundle\Services; use Symfony\Component\DependencyInjectio...」)

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

サンプルサービス作成

-src/Acme/HelloBundle/Services/SampleexampleService.php

namespace Acme\HelloBundle\Services;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
class SampleexampleService
{
   public function __construct(Container $container) {
       $this->container = $container;
   }
   public function exec() {
       echo "exec!!";
   }
}

サービスyml登録

-src/Acme/HelloBundle/Resources/config/services.yml

services:
   acme_hello.sampleexample:
       class:        Acme\HelloBundle\Services\SampleexampleService
       arguments:    [@service_container]

-app/config/config.yml

imports:
   - { resource: "@AcmeHelloBundle/Resources/config/services.yml" }

コントローラから呼び出し

-src/Acme/HelloBundle/Controller/ServiceexampleController.php

namespace Acme\HelloBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class ServiceexampleController extends Controller
{
   public function indexAction()
   {
       $service = $this->container->get('acme_hello.sampleexample');
       $service->exec();
       return $this->render('AcmeHelloBundle:Serviceexample:index.html.twig');
   }
}

twigを一応記述

-src/Acme/HelloBundle/Resources/views/Serviceexample/index.html.twig serviceexample !