[英]How to structure view helper with SQL in Zend Framework 2
我的Zend Framework 2应用程序具有一个视图,通过该视图可以以简单的表格格式显示事件日志。 我使用了几种基本的View Helper来操纵表中数据的表示,但是在这些现有View Viewer上,所有逻辑都包含在View Helper本身中,例如:
namespace Application\View\Helper;
use Zend\View\Helper\AbstractHelper;
class GetSystemName extends AbstractHelper
{
public function __invoke($val)
{
if ($val == 0){
return 'Something';
}
if ($val == 1){
return 'Something else';
}
}
}
我的要求是构建一个函数GetUserName
来接受user_id
并在数据库上执行检查以显示用户名,因为该ID对使用该系统的人没有价值。
我看到的方式可以是:
A)从View Helper中开始新查询以返回我需要的内容,或B getUser()
从“用户”模块/ UserTable
类中使用名为getUser()
的函数。
B的代码是:
namespace User\Model;
use Zend\Db\TableGateway\TableGateway;
class UserTable
{
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
//..other functions
public function getUser($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$row = $rowset->current();
if (!$row) {
throw new \Exception("Could not find row $id");
}
return $row;
}
最好的选择是什么? 我将如何实施呢?
抱歉,如果这是一个基本问题,我对MVC和Zend还是陌生的。
在model-view-controller模式中, 视图不应了解模型层。 来自模型的信息通过控制器注入到视图中。
在模型中让视图助手调用getUser()方法将破坏此模式。
所以你会怎么做?
让您的控制器将用户信息放入视图中:
// controller
$userId = $this->params()->fromQuery("userID");
// or from session ID if this is a private profile page
// You might want some validation, too...
$userTable = $this->getServiceLocator()->get("UserTable");
// or whatever you've configured in the service config for this
$user = $userTable->getUser($userId);
// if this is a public profile page, you might want to
// exclude some fields like "password" so they don't
// accidentally get into the view
$view = new ViewModel();
$view->setVariable("user", $user);
return $view;
然后在view.phtml中,您只需执行以下操作:
<?php $this->GetSystemName($user->whateverField); ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.