打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Zend 2 + Smarty 3 | Sascha Nordquist

Zend 2 + Smarty 3

Ver?ffentlicht von sascha am 6. Februar 2012 Schreibe einen Kommentar (22) Kommentare ansehen

Achtung: Funktioniert nicht mehr mit der Stable Zend 2.0 Version. Siehe Kommentare für funktionierendes SmartyModule und n?tige Modifikationen.

In diesem Artikel wird erkl?rt wie Smarty 3 ins Zend Framework (Version 2) integriert werden kann.

Step 1

Es muss die Datei “vendor/Zend/View/SmartyRenderer.php” erstellt werden:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
<?
namespace Zend\View;
class SmartyRenderer extends PhpRenderer
{
    
    /**
     * Smarty object
     * @var Smarty
     */
    protected $_smarty;
    
    /**
     * Constructor
     *
     * @param string $tmplPath
     * @param array $extraParams
     * @return void
     */
    public function __construct($tmplPath = null, $extraParams = array())
    {
        $this->_smarty = new \Smarty;
        if (null !== $tmplPath) {
            $this->setScriptPath($tmplPath);
        }
        foreach ($extraParams as $key => $value) {
            $this->_smarty->$key = $value;
        }
    }
    /**
     * Return the template engine object
     *
     * @return Smarty
     */
    public function getEngine()
    {
        return $this->_smarty;
    }
    /**
     * Set the path to the templates
     *
     * @param string $path The directory to set as the path.
     * @return void
     */
    public function setScriptPath($path)
    {
        if (is_readable($path)) {
            $this->_smarty->template_dir = $path;
            return;
        }
        throw new Exception('Invalid path provided');
    }
    /**
     * Retrieve the current template directory
     *
     * @return string
     */
    public function getScriptPaths()
    {
        return array($this->_smarty->template_dir);
    }
    /**
     * Assign a variable to the template
     *
     * @param string $key The variable name.
     * @param mixed $val The variable value.
     * @return void
     */
    public function __set($key, $val)
    {
        $this->_smarty->assign($key, $val);
    }
    /**
     * Allows testing with empty() and isset() to work
     *
     * @param string $key
     * @return boolean
     */
    public function __isset($key)
    {
        return null !== $this->_smarty->getTemplateVars($key);
    }
    
    public function __get($key)
    {
        return $this->_smarty->getTemplateVars($key);
    }
    /**
     * Allows unset() on object properties to work
     *
     * @param string $key
     * @return void
     */
    public function __unset($key)
    {
        $this->_smarty->clear_assign($key);
    }
    /**
     * Assign variables to the template
     *
     * Allows setting a specific key to the specified value, OR passing
     * an array of key => value pairs to set en masse.
     *
     * @see __set()
     * @param string|array $spec The assignment strategy to use (key or
     * array of key => value pairs)
     * @param mixed $value (Optional) If assigning a named variable,
     * use this as the value.
     * @return void
     */
    public function assign($spec, $value = null)
    {
        if (is_array($spec)) {
            $this->_smarty->assign($spec);
            return;
        }
        $this->_smarty->assign($spec, $value);
    }
    /**
     * Clear all assigned variables
     *
     * Clears all variables assigned to Zend_View either via
     * {@link assign()} or property overloading
     * ({@link __get()}/{@link __set()}).
     *
     * @return void
     */
    public function clearVars()
    {
        $this->_smarty->clear_all_assign();
    }
    /**
     * Processes a template and returns the output.
     *
     * @param string $name The template to process.
     * @return string The output.
     */
    public function render($name, $vars=null)
    {
        if (null !== $vars) {
            foreach($vars as $k=>$v)
            {
                $this->assign($k,$v);
            }
        }
        $this->file = $this->resolver($name);
        $this->this = $this;
        return $this->getFilterChain()->filter($this->_smarty->fetch($name));
    }
}

Step 2

Nun muss die Datei “module/Application/config/module.config.php” angepasst werden.

Beispiel:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
return array(
    'layout'                => 'layouts/layout.tpl',
    'display_exceptions'    => true,
    'di'                    => array(
        'instance' => array(
            'alias' => array(
                'index' => 'Application\Controller\IndexController',
                'error' => 'Application\Controller\ErrorController',
                'view'  => 'Zend\View\SmartyRenderer',
            ),
            'Zend\View\SmartyRenderer' => array(
                'parameters' => array(
                    'resolver' => 'Zend\View\TemplatePathStack',
                    'options'  => array(
                        'script_paths' => array(
                            'application' => __DIR__ . '/../views',
                        ),
                    ),
                ),
            ),
        ),
    ),
    'routes' => array(
        'default' => array(
            'type'    => 'Zend\Mvc\Router\Http\Segment',
            'options' => array(
                'route'    => '/[:controller[/:action]]',
                'constraints' => array(
                    'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                    'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                ),
                'defaults' => array(
                    'controller' => 'index',
                    'action'     => 'index',
                ),
            ),
        ),
    ),
);

Step 3

Anpassen der Datei “module/Application/Module.php”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php
namespace Application;
// ...
class Module implements AutoloaderProvider
{
    //...
    protected function getView($app)
    {
        if ($this->view) {
            return $this->view;
        }
        $di     = $app->getLocator();
        $view   = $di->get('view', array(
            'tmplPath'=>__DIR__.'/views/',
            'extraParams'=>array('compile_dir'=>'data/templates_c')
        ));
        // ...
        $this->view = $view;
        return $view;
    }
}

Step 4

Anpassen der Datei “module/Application/src/Application/View/Listener.php”

=> Suche und Erstetze “.phtml” mit “.tpl”

Die Datei k?nnte anschlie?end wie folgt aussehen:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
<?php
namespace Application\View;
use ArrayAccess,
    Zend\Di\Locator,
    Zend\EventManager\EventCollection,
    Zend\EventManager\ListenerAggregate,
    Zend\EventManager\StaticEventCollection,
    Zend\Http\PhpEnvironment\Response,
    Zend\Mvc\Application,
    Zend\Mvc\MvcEvent,
    Zend\View\Renderer;
class Listener implements ListenerAggregate
{
    protected $layout;
    protected $listeners = array();
    protected $staticListeners = array();
    protected $view;
    protected $displayExceptions = false;
    public function __construct(Renderer $renderer, $layout = 'layout.tpl')
    {
        $this->view   = $renderer;
        $this->layout = $layout;
    }
    public function setDisplayExceptionsFlag($flag)
    {
        $this->displayExceptions = (bool) $flag;
        return $this;
    }
    public function displayExceptions()
    {
        return $this->displayExceptions;
    }
    public function attach(EventCollection $events)
    {
        $this->listeners[] = $events->attach('dispatch.error', array($this, 'renderError'));
        $this->listeners[] = $events->attach('dispatch', array($this, 'render404'), -1000);
        $this->listeners[] = $events->attach('dispatch', array($this, 'renderLayout'), -80);
    }
    public function detach(EventCollection $events)
    {
        foreach ($this->listeners as $key => $listener) {
            $events->detach($listener);
            unset($this->listeners[$key]);
            unset($listener);
        }
    }
    public function registerStaticListeners(StaticEventCollection $events, $locator)
    {
        $ident   = 'Zend\Mvc\Controller\ActionController';
        $handler = $events->attach($ident, 'dispatch', array($this, 'renderView'), -50);
        $this->staticListeners[] = array($ident, $handler);
    }
    public function detachStaticListeners(StaticEventCollection $events)
    {
        foreach ($this->staticListeners as $i => $info) {
            list($id, $handler) = $info;
            $events->detach($id, $handler);
            unset($this->staticListeners[$i]);
        }
    }
    public function renderView(MvcEvent $e)
    {
        $response = $e->getResponse();
        if (!$response->isSuccess()) {
            return;
        }
        $routeMatch = $e->getRouteMatch();
        $controller = $routeMatch->getParam('controller', 'index');
        $action     = $routeMatch->getParam('action', 'index');
        $script     = $controller . '/' . $action . '.tpl';
        $vars       = $e->getResult();
        if (is_scalar($vars)) {
            $vars = array('content' => $vars);
        } elseif (is_object($vars) && !$vars instanceof ArrayAccess) {
            $vars = (array) $vars;
        }
        $content    = $this->view->render($script, $vars);
        $e->setParam('content', $content);
        return $content;
    }
    public function renderLayout(MvcEvent $e)
    {
        $response = $e->getResponse();
        if (!$response) {
            $response = new Response();
            $e->setResponse($response);
        }
        if ($response->isRedirect()) {
            return $response;
        }
        $vars = $e->getResult();
        if (is_scalar($vars)) {
            $vars = array('content' => $vars);
        } elseif (is_object($vars) && !$vars instanceof ArrayAccess) {
            $vars = (array) $vars;
        }
        if (false !== ($contentParam = $e->getParam('content', false))) {
            $vars['content'] = $contentParam;
        }
        $layout   = $this->view->render($this->layout, $vars);
        $response->setContent($layout);
        return $response;
    }
    public function render404(MvcEvent $e)
    {
        $vars = $e->getResult();
        if ($vars instanceof Response) {
            return;
        }
        $response = $e->getResponse();
        if ($response->getStatusCode() != 404) {
            // Only handle 404's
            return;
        }
        $vars = array(
            'message'            => 'Page not found.',
            'exception'          => $e->getParam('exception'),
            'display_exceptions' => $this->displayExceptions(),
        );
        $content = $this->view->render('error/404.tpl', $vars);
        $e->setResult($content);
        return $this->renderLayout($e);
    }
    public function renderError(MvcEvent $e)
    {
        $error    = $e->getError();
        $app      = $e->getTarget();
        $response = $e->getResponse();
        if (!$response) {
            $response = new Response();
            $e->setResponse($response);
        }
        switch ($error) {
            case Application::ERROR_CONTROLLER_NOT_FOUND:
            case Application::ERROR_CONTROLLER_INVALID:
                $vars = array(
                    'message'            => 'Page not found.',
                    'exception'          => $e->getParam('exception'),
                    'display_exceptions' => $this->displayExceptions(),
                );
                $response->setStatusCode(404);
                break;
            case Application::ERROR_EXCEPTION:
            default:
                $exception = $e->getParam('exception');
                $vars = array(
                    'message'            => 'An error occurred during execution; please try again later.',
                    'exception'          => $e->getParam('exception'),
                    'display_exceptions' => $this->displayExceptions(),
                );
                $response->setStatusCode(500);
                break;
        }
        $content = $this->view->render('error/index.tpl', $vars);
        $e->setResult($content);
        return $this->renderLayout($e);
    }
}

Step 5

Entpacke Smarty 3 nach vendor/smarty/

Step 6

Zum schluss muss nurnoch die “index.php” angepasst werden.

1
2
3
4
5
6
7
//...
require_once (getenv('ZF2_PATH') ?: 'vendor/ZendFramework/library') . '/Zend/Loader/AutoloaderFactory.php';
Zend\Loader\AutoloaderFactory::factory(array('Zend\Loader\StandardAutoloader' => array()));
include('vendor/smarty/Smarty.class.php');
include('vendor/Zend/View/SmartyRenderer.php');
// ...

 

Kommentar schreiben

22 Kommentare.

  1. Hallo,

    gibts denn schon eine überarbeitete Version oder eine Idee warum es nicht (mehr) funktioniert? Habe mich ehrlich gesagt noch nicht mit dem ZF2 auseinander gesetzt, werde aber umsteigen, sobald es mal einen richtigen release gibt. Dann würde ich allerdings gerne direkt auch auf das aktuellste Smarty upgraden, da bietet sich dies hier natürlich an.

    Domi

  2. Das hat nur für die Beta Version funktioniert.
    In der Stable Version gab es ein paar gr??ere ?nderungen, wodurch das hier nicht mehr funktioniert.
    Ich hatte bisher auch noch keine Zeit es wieder zum laufen zu bekommen.

  3. Ich habe Smarty 3 in Verbindung mir dem aktuellen Zend 2 Release vom 04.09.2012 mit dem SmartyModule von
    https://github.com/MurgaNikolay/SmartyModule

    in Verbindung mit:
    https://github.com/MurgaNikolay/ZendSkeletonApplication

    nach ein paar kleineren Anpassungen zum Laufen bekommen.

  4. Interessantes modul. Hab es auch soweit zum Laufen gekriegt, dass mal alles so fehlerfrei included wird und das modul in der application.config.php aktiviert, allerdings fehlt mir jetzt grad der entscheidende Tipp, was noch zu tun ist, dass er auch die .tpl files liest und anzeigt?

  5. Meine Module Klasse sieht wie folgt aus:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    class Module
    {
        public function onBootstrap($e) {
            $this->initializeView($e);    
                    // ...
        }
        // some other stuff...
        public function initializeView($e)
        {
            global $config;
            $app          = $e->getParam('application');
            $request = $app->getRequest();
            // support cli requests which do not have a base path
            if (method_exists($request, 'getBasePath')) {
                $basePath     = $app->getRequest()->getBasePath();
            }
            $serviceManager      = $app->getServiceManager();
            $view         = $serviceManager->get('Zend\View\View');
            $strategy     = $serviceManager->get('SmartyModule\View\Strategy\SmartyStrategy');
            $renderer = $strategy->getRenderer();
            $resolver = $serviceManager->get('viewresolver');
            $renderer->setResolver($resolver);
            
            $smarty = $renderer->getEngine();
            $config = $serviceManager->get('Config');
            if ($config['environment'] == "production") {
                $smarty->compile_check = false;
                $smarty->force_compile = false;
            }
            
            $renderer->setHelperPluginManager(new HelperPluginManager(new HelperConfig()));
            $config = $serviceManager->get('config');
            $router = \Zend\Mvc\Router\SimpleRouteStack::factory($config['router']);
            $renderer->plugin('url')->setRouter($router);
            
            if (isset($basePath)) {
                $renderer->plugin('basePath')->setBasePath($basePath);
            }
        }
    }

    My “module.config.php” sieht etwa so aus:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    return array(
        'alias' => array(
            'view' => 'SmartyModule\View\Renderer\SmartyRenderer',
        ),
            // ...
        'view_manager' => array(
            'display_not_found_reason' => true,
            'display_exceptions'       => true,
            'doctype'                  => 'HTML5',
            'defaultSuffix'               => '.tpl',
            'not_found_template'       => 'error/404',
            'exception_template'       => 'error/index',
            'template_map' => array(
                'layout/layout'           => ROOT_DIR . '/view/layout/layout.tpl',
                'error/404'               => ROOT_DIR . '/view/error/404.tpl',
                'error/index'             => ROOT_DIR . '/view/error/index.tpl',
            ),
            'template_path_stack' => array(
                ROOT_DIR . '/view',
            ),
        ),
        // ...
    );

    Wobei ROOT_DIR eine selbst definierte Konstante ist, die man auch durch __DIR__ ersetzen kann, je nachdem wo der Template Ordner liegen soll.

  6. Hey Sascha,

    du hilfst mir schon gut weiter! Aber was ich noch nicht verstehe: warum “benutzt” die SmartyStrategy aus dem SmartyModule das Zend\EventManager\ListenerAggregate wenn es dieses garnicht gibt?! hast du das in deiner Version selbst gebaut und eingebunden?

    Vielen Dank für die Hilfe und ich hoffe, wir bekommen es noch zum Laufen

    Gru?
    Domi

    • Hi,

      ja, hab vergessen, dass ich die Klasse angepasst habe.
      Die Klassen ListerAggregate und EventCollection gibts nicht mehr.

      Die SmartyStrategy sieht also so aus:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      namespace SmartyModule\View\Strategy;
      use Zend\EventManager\EventCollection,
          Zend\EventManager\EventManagerInterface,
          Zend\EventManager\ListenerAggregateInterface,
          Zend\View\ViewEvent,
          SmartyModule\View\Renderer\SmartyRenderer;
      class SmartyStrategy implements ListenerAggregateInterface {
          protected $renderer;
          protected $listeners = array();
          public function __construct(SmartyRenderer $renderer)
          {
              $this->renderer = $renderer;
          }
          public function attach(EventManagerInterface $events) {
              $this->listeners[] = $events->attach('renderer', array($this, 'selectRenderer'));
              $this->listeners[] = $events->attach('response', array($this, 'injectResponse'));
          }
          public function detach(EventManagerInterface $events)
          {
              foreach ($this->listeners as $index => $listener) {
                  if ($events->detach($listener)) {
                      unset($this->listeners[$index]);
                  }
              }
          }
          // ...

      Die Klasse SmartyRenderer hat auch Anpassungen:

      • Zend\View\Model\Model -> Zend\View\Model\ModelInterface

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      use Zend\View\Renderer\PhpRenderer,
          Zend\View\Exception,
          Zend\View\Model\ModelInterface,
          ArrayAccess;
      class SmartyRenderer extends PhpRenderer
      {
          // ...
          public function render($nameOrModel, $values = null)
          {
              if ($nameOrModel instanceof ModelInterface) {
                  $model = $nameOrModel;
                  $nameOrModel = $model->getTemplate();
                  if (empty($nameOrModel)) {
                      throw new Exception\DomainException(sprintf(
                          '%s: received View Model argument, but template is empty',
                          __METHOD__
                      ));
                  }
                  $options = $model->getOptions();
                  foreach ($options as $setting => $value)
                  {
                      $method = 'set' . $setting;
                      if (method_exists($this, $method)) {
                          $this->$method($value);
                      }
                      unset($method, $setting, $value);
                  }
                  unset($options);
                  // Give view model awareness via ViewModel helper
                  $helper = $this->plugin('view_model');
                  $helper->setCurrent($model);
                  $values = $model->getVariables();
                  unset($model);
              }
              // find the script file name using the parent private method
              $this->addTemplate($nameOrModel);
              unset($nameOrModel); // remove $name from local scope
              if (null !== $values) {
                  $this->setVars($values);
              }
              unset($values);
              // extract all assigned vars (pre-escaped), but not 'this'.
              // assigns to a double-underscored variable, to prevent naming collisions
              $__vars = $this->vars()->getArrayCopy();
              $__vars['this'] = $this;
              $this->smarty->assign($__vars);
              while ($this->__template = array_pop($this->__templates))
              {
                  $this->__file = $this->resolver($this->__template);
                  if (!$this->__file) {
                      throw new Exception\RuntimeException(sprintf(
                          '%s: Unable to render template "%s"; resolver could not resolve to a file',
                          __METHOD__,
                          $this->__template
                      ));
                  }
                  $tmplDir = dirname(dirname($this->__file));
                  $this->smarty->setTemplateDir($tmplDir);
                  $this->__content = $this->smarty->fetch($this->__file);
              }
              return $this->getFilterChain()->filter($this->__content); // filter output
          }
          // ...
      }

      • oh Sascha,

        ich trau mich garnicht dich weiter zu nerven..


        Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for SmartyModule\View\Strategy\SmartyStrategy' in ...../vendor/ZF2/library/Zend/ServiceManager/ServiceManager.php:420 Stack trace: #0 ...../module/SmartyModule/Module.php(28) ...

        bin mir aber eigtl sicher, dass er auf das File zugreifen kann, daher ist mir das nicht so ganz erkl?rlich, warum er da nicht weiter kommt ..

        Viiiiielen Dank soweit für die Hilfe, viel kanns jetzt ja nicht mehr sein.

        Werde das resultat wenns l?uft auf jeden Fall zur Verfügung stellen auf gitHub.

          • irgendwo anders war der Hund begraben.. hatte scheinbar schon zuviel ge?ndert. Hab die Quellen mal neu geladen. Nun geht die Suche weiter: Den

            Zend\Module\Consumer\AutoloaderProvider

            der in der Module.php verwendet wird, den die class Module implementiert scheint es ja auch nicht mehr zu geben. Habe es nun mal so gemacht, passt das?


            namespace SmartyModule;

            use Zend\ModuleManager\ModuleManager,
            Zend\ModuleManager\Feature\AutoloaderProviderInterface,
            Zend\EventManager\StaticEventManager;

            class Module implements AutoloaderProviderInterface
            {
            //...

            Er zeigt mir nun die richtige layout.tpl an, allerdings l?uft diese scheinbar nicht durch smarty durch. Und scheinbar ruft er auch die render() im SmartyRenderer nicht auf. Irgendwas fehlt also noch ..

            die Smarty.class.php wird allerdings irgendwann mal initialisiert, das scheint zu klappen ..

            Noch Ideen?

          • Hi,

            die Module Klassen müssen garkein Interface mehr implementieren:

            Meine SmartyModule\Module Klasse sieht wie folgt aus:

            1
            2
            3
            4
            5
            6
            7
            8
            9
            10
            11
            12
            13
            14
            15
            16
            17
            18
            19
            20
            21
            22
            23
            24
            25
            26
            27
            28
            29
            30
            31
            32
            33
            34
            35
            36
            37
            38
            39
            namespace SmartyModule;
            use Zend\Module\Manager,
                 Zend\EventManager\StaticEventManager;
            class Module {
                public function onBootstrap($e) {
                    $this->setupView($e);
                }
                /**
                 * @param $e
                 */
                public function setupView($e) {
                      $application = $e->getParam('application');
                      $serviceManager             = $application->getServiceManager();
                      $view                = $serviceManager->get('Zend\View\View');
                      $smartyRendererStrategy = $serviceManager->get('SmartyModule\View\Strategy\SmartyStrategy');
                      $view->addRenderingStrategy(array($smartyRendererStrategy, 'selectRenderer'), 100);
                      $view->addResponseStrategy(array($smartyRendererStrategy,  'injectResponse'), 100);
                }
                public function getAutoloaderConfig() {
                    return array(
                        'Zend\Loader\ClassMapAutoloader' => array(
                            __DIR__ . '/autoload_classmap.php',
                        ),
                        'Zend\Loader\StandardAutoloader' => array(
                            'namespaces' => array(
                                __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                            ),
                        ),
                    );
                }
                public function getConfig() {
                    return include __DIR__ . '/config/module.config.php';
                }
            }

  7. Wichtig für den Controller ist noch, dass man ein ViewModel benutzt:

    Beispiel:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    use Zend\Mvc\Controller\AbstractActionController,
        Zend\View\Model\ViewModel;
    class IndexController extends AbstractActionController {
        public function indexAction() {
            $view = new ViewModel;
            $view->someVariable = "someContent";
            return $view;
        }
    }

    • im controller habe ich:

      return new ViewModel(
      array(
      ‘hello’ => ‘hello world. smarty works?!’,
      )
      );

      aber was er mir jetzt noch bringt:

      fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException' with message 'SmartyModule\View\Renderer\SmartyRenderer::render: Unable to render template "application/index/index"; resolver could not resolve to a file

      er kanns scheinbar also nicht aufl?sen. Hab mal versucht in den Klassen vom Zend phprenderer reinzuschauen aber springt er mir an einer stelle raus, an der ich es nicht erwartet habe. evtl kannst du mal über das modul nochmal drüber schauen?

      https://github.com/Domi-cc/SmartyModule

      w?re super gut von dir!

      Domi

      • ah, so gehts:

        public function onBootstrap($e) {
        $this->initializeView($e);
        $this->setupView($e);
        }

        aber falls doch noch was anzumerken hast, gerne

        was er noch anmeckert wenn ichs nicht rauswerfe ist:

        $renderer->setHelperPluginManager(new HelperPluginManager(new HelperConfig()));
        $config = $serviceManager->get(‘config’);
        $router = \Zend\Mvc\Router\SimpleRouteStack::factory($config['router']);
        $renderer->plugin(‘url’)->setRouter($router);

        Fatal error: Class 'SmartyModule\HelperPluginManager' not found in ..

        .. hast du den selber geschrieben noch?

        • Hi,

          nein das habe ich nicht selbst geschrieben. Wenn du diese “uses” rein machst, sollte es gehen:

          1
          2
          3
          4
          use Zend\ModuleManager\ModuleManager as Manager,
              Zend\EventManager\StaticEventManager,
              Zend\View\HelperPluginManager,
              Zend\Form\View\HelperConfig;

          Dadurch kannst du die Zend\Form View Helper verwenden:

          z.b.:

          1
          {$this->form()->openTag($form)}

          Das Url Plugin ist dafür da, dass man im Smarty über den Router die Urls bauen kann:

          <a href=”{$this->url(…)}”>…</a>

  8. Hi
    Sorry, I’m french, and really not good in German, so I try in english


    I’m trying to use your tutorial but i’m a bit lost with all these code updates. I have some fatal error and I can’t figure out where I missed something !
    Is it possible to give the full code of the module with your updates ?
    Thanks a lot for this tutorial, you’re one of the only ones that I found on the web

    • Hi,

      no problem, just wait a bit until Domi has made all fixes to https://github.com/Domi-cc/SmartyModule
      or just ask your question in english.

      • Thanks


        I retrieved the module fixed and installed on a skeletton application.
        After I updated the application.config.php file like this :

        return array(
        ‘modules’ => array(
        ‘Application’,
        ‘SmartyModule’,
        ),
        // …
        );

        I have this error :

        Fatal error: Uncaught exception ‘Zend\ServiceManager\Exception\ServiceNotFoundException’ with message ‘Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Literal’ in C:\cch\zf2-smarty\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php

        I’m new to Zend, so I’m not sure to have installed it correctly

        . If you have an idea ?

        • Oh , Domi made another update, it’s a lot better

          it seems to work now.
          Thanks a lot to both of you, you saved my day

          • You’re invited to improve it with me together. just fork it on github and commit your changes with a pull request.

            Thank you

            Domi

          • Hi Domi !
            I don’t know how to use github yet, when I have a little time I’ll commit my changes. I just added a block in the SmartyRenderer class, in the render method :

            // changes default suffix from “phtml” to “tpl”
            foreach ($this->resolver() as $resolver)
            if (get_class($resolver) == “Zend\View\Resolver\TemplatePathStack”)
            $resolver->setDefaultSuffix(‘tpl’);

            There’s surely a more elegant way to do it, but it is useful not to have to manually declare all my templates in the config file.

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
Zend Framework 2.0的Mvc结构及启动流程分析
Crash Course
ECshop模板机制整理
Introduction to PHP for theming | drupal.org
ECshop网站模板修改详细教程 and 模板对应的文件
详解模板渲染引擎 jinja2
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服