我创建了一个库,它将加载一个php文件(其中可能包含用户自定义函数…),您可以从bootstrap也可以从控制器调用它。如果文件不存在,它将显示错误消息。问题是我是用现在的方式做的吗?
如果我错过了什么,请指出来。由于Helpers是用户可以放置php文件的文件夹
app/
controllers/
models/
helpers/
library/
views/
在"library/"文件夹中有一个名为"helperfile.php"的php文件
class helperfile extends Phalcon'Mvc'User'Component
{
var $helper_Folder = '../app/helpers';
var $files = array();
public function __construct()
{
}
public function initialize()
{
}
public function include_file($files, $run = true)
{
if (!is_array($files))
$files = array($files);
foreach ($files as $file)
$this->files[$file] = $file;
if ($run)
$this->load();
}
public function beforeDispatch()
{
$this->load();
}
private function load()
{
if (empty($this->files))
return false;
foreach ($this->files as $file) {
$file = trim($file) . '.php';
if ($this->is_file_exists($file)) {
require $this->helper_Folder . '/' . $file;
}
}
}
private function is_file_exists($path)
{
$full_path = $this->helper_Folder . '/' . $path;
if (!file_exists($full_path)) {
$this->flash->error("Helper File Missing: " . $full_path);
return false;
}
return true;
}
}
//通过bootstrap ("public/index.php")在每个页面上自动加载文件
$di->set('dispatcher', function () {
//Create/Get an EventManager
$eventsManager = new Phalcon'Events'Manager();
/*
* Load Custom function files which are in the helpers folder
*/
$loadHelper = new helperfile();
$loadHelper->include_file([
'calling_from_bootstrap_1',
'calling_from_bootstrap_2'
],false);
$eventsManager->attach('dispatch', $loadHelper);
$dispatcher = new Phalcon'Mvc'Dispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
});
//从控制器
加载$loadHelper = new helperfile();
$loadHelper->include_file([
'calling_from_theController'
]);
看起来应该可以,但是我认为你低估了Phalcon能为你做的工作量。
帮助文件中的一个示例将是有用的。对于这个例子,我假设它是这样的:
app/
helpers/
ProductHelper.php
和ProductHelper.php
class ProductHelper{
// code here
}
在你的bootstrap中你有加载器你定义你的目录
$phalconLoader = new 'Phalcon'Loader();
/**
* We're a registering a set of directories taken from the configuration file
*/
$phalconLoader->registerDirs(
array(
$phalconConfig->application->controllersDir,
$phalconConfig->application->modelsDir,
// path to helper dir here
)
)->register();
然后在控制器
中public function productAction(){
$productHelper = new productHelper();
}
应该可以。它的代码更少,所以更简单,应该运行得更快一点(使用phalcon的内置代码,而不是写一些php总是会更快)
如果帮助程序中的代码不在类中,或者与文件名命名不相同,那么它可能应该是。让事情简单多了。
Di Enabled Version
class ProductHelper extends 'Phalcon'DI'Injectable{
public $config;
public function myFunction(){
$this->config = $this->getDI ()->get ('config');
}
}
和控制器
public function indexAction()
{
$helper = new ProductHelper();
$helper->setDI($this->getDI());
$helper->myFunction();
}
或者在创建DI
时$di->set ('productHelper', function () use ($config, $di) {
$helper = new ProductHelper();
$helper->setDi ($di);
return $helper;
});
和控制器
public function indexAction()
{
$helper = new ProductHelper();
$helper->myFunction();
}