Zend Framework2.3.3入门简单实例-注册功能

要用Zend Framework2.3.3实现一个注册功能也甚为简单。前面几步跟登录功能是一样的,包括数据库和ServiceManager配置、Model等等。这里便不再赘述。

一、From类

与实现登录功能一样,在\module\Application\src\Application\Form下建一个AccountRegisterForm,需在继承Form。

use Zend\Form\Form;

class AccountRegisterForm extends Form {
	public function __construct() {
		parent::__construct();
		
		$this->add(array(
				"name" => "id",
				"type" => "Hidden",
		));
		$this->add(array(
				"name" => "name",
				"type" => "Text",
				"options" => array(
						"label" => "User Name:",
						"id" => "name",
				),
		));
		$this->add(array(
				"name" => "pwd",
				"type" => "Text",
				"options" => array(
						"label" => "Password:",
						"id" => "pwd"
				),
		));
		$this->add(array(
				"name" => "cpwd",
				"type" => "Text",
				"options" => array(
						"label" => "Confirm Password:",
						"id" => "cpwd"
				),
		));
		$this->add(array("name" => "submit",
				"type" => "Submit",
				"attributes" => array(
						"value" => "Go",
						"id" => "submitbutton",
				),
		));
	}
}

二、路由配置

参照登录功能的路由配置,添加如下信息到\module\Application\config\module.config.php文件

'register' => array(
	'type' => 'Zend\Mvc\Router\Http\Literal',
	'options' => array(
		'route'    => '/account/register',
		'defaults' => array(
			'controller' => 'Album\Controller\Index',
			'action'     => 'accountregister',
		),
	),
),
三、Controller处理

像登录的Controller一样,需要另外调用一个function getAccountTable()来操作数据库。

public function getAccountTable()
{
    if(!$this->accountTable) {
	$sm = $this->getServiceLocator();
	$this->accountTable = $sm->get("Album\Model\Account");
    }
    return $this->accountTable;
}
像登录功能实现一样,写一个Action方法,实现注册功能处理。
public function AccountRegisterAction()
{
	$form = new AccountRegisterForm();
	$form->get("submit")->setValue("Register");
		
	$request = $this->getRequest();
	if($request->isPost()) {
		$account = new Account();
		$form->setInputFilter($account->getInputFilter());
		$form->setData($request->getPost());
		
		if ($form->isValid()) {
			$account->exchangeArray($form->getData());
			$this->getAccountTable()->saveAccount($account);
				
			// Redirect to list of albums
			return $this->redirect()->toRoute("login");
		}
	}
	return array("form" => $form);
}
四、View

这里需要建一个AccountRegister.phtml文件,与Action对应。如下

headTitle($title);
?>

escapeHtml($title); ?>

setAttribute('action', $this->url('register', array('action' => 'add'))); $form->prepare(); echo $this->form()->openTag($form); echo $this->formHidden($form->get('id'))."
"; echo $this->formRow($form->get('name'))."
"; echo $this->formRow($form->get('pwd'))."
"; echo $this->formSubmit($form->get('submit'))."
"; echo $this->form()->closeTag();

至此便完成了注册功能的实现,运行,效果如下:


在这里当我们输入admin/admin之后会进入登录页面,因为我们在action中是这样写的return $this->redirect()->toRoute("login");跳转的路由是login,我们在登录功能时配置的那个。

原文地址:http://www.wenotebook.com/Article/Index?articleID=2014122113152

你可能感兴趣的:(PHP,ZendFramework)