您的位置:首页 > 编程语言 > PHP开发

Zend Framework 2 Helloword 入门实例

2014-10-30 18:00 751 查看
Zend Framework 2 出来已经有一段时间了,网上也出来了相应的教程。本人也学习了一定的时间,特此把自己能学到的东西记录下来。

本人是新手,难免会有纰漏之处,若有不足之处望大家指正。

本实例是一个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)

<?php
namespace 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 )

<?php

return 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)

<?php
namespace 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 )

<?php
return 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了;

helloword 程序下载:https://github.com/mushroot/zf2-helloword
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息