如何制作一个处理和呈现不同页面的操作

时间:2014-02-27 12:05:22

标签: php zend-framework2

zf2中是否有可能只有一个控制器和一个可以重复用于不同页面的动作?

称。

   Class SiteController extends AbstractActionController{


    public function viewAction(){

       // use for the homepage, product, category etc pages.


    }


    }

这可能吗?

2 个答案:

答案 0 :(得分:3)

可以使用参数加载不同的内容。

类SiteController扩展了AbstractActionController {

    public function viewAction(){
       $content = $this->params()->fromRoute('slug');

       // Query or logic using slug to load different content dynamically

    }
}

module.config.php

        'router' => array(
            'routes' => array(
                    'site' => array(
                            'type'    => 'literal',
                            'options' => array(
                                    'route'    => '/site',
                                    'defaults' => array(
                                            'controller' => 'Application\Controller\SiteControllerr',
                                            'action'     => 'index',
                                    ),
                            ),
                            'may_terminate' => true,
                            'child_routes' => array(
                                'view' => array(
                                    'type' => 'segment',
                                    'options' => array(
                                        'route' => '/[:slug]',
                                        'constraints' => array(
                                            'slug' => '[a-zA-Z0-9_-]+'
                                        ),
                                        'defaults' => array(
                                            'action' => 'view'
                                        )
                                    )
                                ),
                            ),
                    ),
            ),
    ),

现在你可以拥有像

这样的路线

/站点/产品 /站点/类别

答案 1 :(得分:1)

我和ZF2一起使用了PimCore,我遇到了同样的问题,每个控制器都特定于某个视图,我想通过查看Zend_View类一段时间我可以创建一个'loadView'解决这个问题的方法:

/**
     * Load and render an arbitrary view.
     * Path is set to the ./website/views/scripts/
     * @param string $name name / path of the view relative to ./website/views/scripts/ (No leading /)
     * @param array $params key => value assoc array of variables to be passed to the view.
     * @return string rendered view string.
     */
    protected function loadView($name, $params=array()) {
        $view = new Zend_View(array('scriptPath' => './website/views/scripts/'));

        if(is_object($params))
            $params = (array)$params;

        foreach($params as $key => $value)
            $view->assign($key, $value);

        return $view->render($name);
    }

这对你也有用。

编辑** 当然,您可能需要将基本路径更改为您的视图文件......:)

相关问题