春咲さんのメモ。

自分メモ的な。主にPHPについて。github:mindlessdoll(冬眠してるけど)

Symfony2で作ったサービスをTwigで利用する

1.サービス(もどき)を作る

2.TwigExtensionを拡張する

3.Twigで使う

 といった感じで進めていきます。

1.サービスもどきを作る

 今回私が作ったのはSEO用の文字列を取得する関数。共通で使いたかったので、Lib配下にSeoBundleを作成。内容は割愛。

2.TwigExtensionを拡張する

 これはちゃんと書くよ!↓中身

namespace hoge\fugaBundle\Twig\Extensions;

use Symfony\Component\DependencyInjection\ContainerInterface;
use \Twig_Extension;
use \Twig_Function_Method;

/**
 * TemplatingExtension
 * Twigの拡張クラス
 *
 */
class TemplatingExtension extends Twig_Extension
{

    /**
     * コンストラクタ
     *
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function getFunctions()
    {
        return array(
            'service' => new Twig_Function_Method($this, 'getService'),
        );
    }

    /**
     * DIコンテナを取得する
     *
     * @param ContainerInterface $container
     */
    public function getContainer()
    {
        return $this->container;
    }

    /**
     * DIコンテナからサービスを取得する
     *
     *
     * @param string $name サービス名
     * @return mixed サービスインスタンス
     */
    public function getService($name)
    {
        return $this->container->get($name);
    }

    public function getName()
    {
        return 'twig_extension';
    }
}

Services.yml

parameters:
    xx.twig.class: hoge\fugaBundle\Twig\Extensions\TemplatingExtension

services:
    xx.twig.templating_extension:
        class: "%xx.twig.class%"
        tags:
          - { name: twig.extension }
        arguments:
            - @service_container

2はこんな感じで。

3.Twigで使う

{% set seo = service('Seo') %}
{% set headers = seo.getHeaders(param) %}
{{ headers.title }}
{{ headers.description }}

こんな感じです。

getServiceってFunctionをserviceというタグで呼び出せるように定義しました。その名の通りな機能です。

getHeadersはサービスの中にあるfuncitonです。

今回一番はまったのは…Extensionの綴りですかねぇ…ずっとExtentionって書いてて動かないと悩んでおりましたので…。