我正在尝试使用phalcon here的基本示例复制Volt教程here中的示例,所以没有什么复杂的。
所以我创建了这样的app / controllers / PostsControllers:
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
/* $post = Post::findFirst();
$menu = Menu::findFirst();*/
$post = array("title"=>"The titre");
$menu = "menu1";
$this->view->show_navigation = true;
$this->view->menu = $menu;
$this->view->title = $post["title"];
$this->view->post = $post;
// Or...
$this->view->setVar('show_navigation', true);
$this->view->setVar('menu', $menu);
$this->view->setVar('title', $post["title"]);
$this->view->setVar('post', $post);
}
}
它的相应app / views / posts / index.phtml是这样的:
{# app/views/posts/show.phtml #}
<!DOCTYPE html>
<html>
<head>
<title>{{ title }} - An example blog</title>
</head>
<body>
{% if show_navigation %}
<ul id='navigation'>
{% for item in menu %}
<li>
<a href='{{ item.href }}'>
{{ item.caption }}
</a>
</li>
{% endfor %}
</ul>
{% endif %}
<h1>{{ post.title }}</h1>
<div class='content'>
{{ post.content }}
</div>
</body>
</html>
我还在我的引导文件(/public/index.php)中注册了伏特,看起来像这样:
<?php
use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt;
// Register an autoloader
$loader = new Loader();
$loader->registerDirs(
[
"../app/controllers/",
"../app/models/",
]
);
$loader->register();
// Create a DI
$di = new FactoryDefault();
// Setup the view component
$di->set(
"view",
function () {
$view = new View();
$view->setViewsDir("../app/views/");
$view->registerEngines(
[
'.volt' => 'voltService',
]
);
return $view;
}
);
// Setup a base URI so that all generated URIs include the "tutorial" folder
$di->set(
"url",
function () {
$url = new UrlProvider();
$url->setBaseUri("/care/");
return $url;
}
);
$application = new Application($di);
try {
// Handle the request
$response = $application->handle();
$response->send();
} catch (\Exception $e) {
echo "Exception: ", $e->getMessage();
}
但是当我尝试访问/posts
目录(localhost/care/posts
)时,我收到以下错误:
异常:在依赖注入容器中找不到服务'voltService'
我检查了Volt服务是否已在Services.php
中声明,因为它在类似的帖子here中说过,但事实并非如此。
谢谢
答案 0 :(得分:2)
问题在于这段代码。您告诉您的观点是它应该使用volt
扩展名并使用名为voltService
的服务来处理它。
// Setup the view component
$di->set(
"view",
function () {
$view = new View();
$view->setViewsDir("../app/views/");
$view->registerEngines(
[
'.volt' => 'voltService',
]
);
return $view;
}
);
如果您查看自己的代码段,则没有定义名为voltService
的服务。
但是,如果您将此添加到您的服务中,它应该有效:
// Register Volt as a service
$di->set(
'voltService',
function ($view, $di) {
$volt = new Volt($view, $di);
$volt->setOptions(
[
'compiledPath' => '../app/compiled-templates/',
'compiledExtension' => '.compiled',
]
);
return $volt;
}
);