我已经创建了自己的框架来开发我的个人投资组合网站。我将它(非常)松散地基于我相当熟悉的 Zend Framework。除了在控制器中设置变量之外,我已经设法让事情正常工作,然后可以在 .phtml 文件中使用这些变量。这就是我目前所拥有的(例如,这里的 url 是 www.mydomain.com/services/hosting):
前台.php
class front {
private $sControllerName = 'home';
private $sActionName = 'index';
function __construct() {
$this->view = new viewProperties();
$aUriParts = $this->getUriParts();
if (!empty($aUriParts[0])) {
$this->sControllerName = $aUriParts[0];
}
if (!empty($aUriParts[1])) {
$this->sActionName = $aUriParts[1];
}
$this->constructController();
include('path/to/views/view.phtml');
}
private function constructController() {
$sContFile = 'controllers/'.$this->sControllerName.'.php';
if (@include($sContFile)) {
$c = new $this->sControllerName();
// Action method, if exists
$this->doAction($c);
}
}
public function getElement($name) {
include('public_html/elements/'.$name);
}
public function renderContent() {
$sViewFile = 'path/to/views/'.$this->sControllerName;
if ($this->sActionName) {
$sViewFile .= '/'.$this->sActionName.'.phtml';
} else {
$sViewFile .= '.php';
}
if (!@include($sViewFile)) {
$this->render404();
}
}
private function doAction($c) {
$sActionFunc = str_replace('-', '_', $this->sActionName.'Action');
if (method_exists($c,$sActionFunc)) {
$c->$sActionFunc();
}
}
private function render404() {
include('path/to/views/404.phtml');
}
private function getUriParts() {
$sUri = $_SERVER['REQUEST_URI'];
$sUri = trim($sUri, "/");
$sUri = str_replace("-", "_", $sUri);
$aUriParts = explode("/", $sUri);
return $aUriParts;
}
}
视图属性.php
class viewProperties {
static $_instance = null;
private $data = array();
public static function getInstance() {
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function __set($name, $value) {
echo "Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}
public function __get($name) {
echo "Getting '$name'\n";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
}
public function __isset($name) {
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}
public function __unset($name) {
echo "Unsetting '$name'\n";
unset($this->data[$name]);
}
}
服务.php
class services extends controller {
public function indexAction() {
$this->view->banner->src = '/path/to/images/banners/home_02.jpg';
$this->view->banner->alt = 'banner title';
}
public function hostingAction() {
$this->view->banner->src = '/path/to/images/banners/home_02.jpg';
$this->view->banner->alt = 'banner title';
}
}
在hosting.phtml我有:
<img src="<?php echo $this->view->banner->src ?>" alt="<?php echo $this->view->banner->title ?>" />
如何在控制器中设置属性(不仅仅是横幅),然后在视图中检索它们?帮助/指导将不胜感激。