【ZF2】Zend Framework 2 Helloword 入门实例

来源:互联网 发布:迪昂维特斯数据 编辑:程序博客网 时间:2024/04/29 19:08

本实例是一个hello word例子(本实例基于2.2.1版本构建,前提是你已经搭建好了本框架)

step 1:

在 Moduel 目录下建立我们的新模块 Helloword,并建立如下文件目录

/ Moduel/ Helloword / config/ src/ Helloword/ Controller/Model/ view/ helloword/helloword

step 2:

建立 Module.php 文件 (path:/module/Helloword/Module.php)

<?phpnamespace Helloword;class Module{public function getAutoloaderConfig(){return array('Zend\Loader\StandardAutoloader' => array('namespaces' => array(__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,),),);}public function getConfig(){return include __DIR__ . '/config/module.config.php';}}

step 3:

建立 module.config.php 文件 ( path:/module/Helloword/config/module.config.php )

<?phpreturn array('controllers' => array('invokables' => array('Helloword\Controller\Helloword' => 'Helloword\Controller\HellowordController',),),'view_manager' => array('template_path_stack' => array('album' => __DIR__ . '/../view',),),);

step 4:

在主模块中添加当前模块
打开:config/application.config.php文件
找到

'modules' => array('Application',),

在其中添加helloword模块,即修改为

'modules' => array('Application','Helloword',),

step 5:

在建立我们的第一个控制器:HellowordController.php (path:/module/helloword/src/Helloword/Controller/HellowordController.php)

<?phpnamespace Helloword\Controller;use Zend\Mvc\Controller\AbstractActionController;use Zend\View\Model\ViewModel;class HellowordController extends AbstractActionController{public function indexAction(){return new ViewModel(array('hello' => 'hi'));}}

step 6:

建立视图文件 index.phtml(这个视图文件同HellowordController::indexAction对应)
( path: /module/Helloword/view/helloword/helloword/index.phtml )

<?php  echo $this->hello;?>这是一个helloword程序

输出:

hi这是一个helloword程序

step 7:

设置路由使得我们能够访问

( path: /module/Helloword/config/module.config.php )

<?phpreturn array('router' => array('routes' => array('helloword' => array('type'    => 'segment','options' => array('route'    => '/helloword[/:action]','constraints' => array('action' => '[a-zA-Z][a-zA-Z0-9_-]*',),'defaults' => array('controller' => 'helloword\Controller\helloword','action'     => 'index',),),),)),......);

最后就可以访问:site/helloword了;

0 0
原创粉丝点击