几周以来,我一直在使用 Zend Framework 2,尽管在线文档非常不完整,但我还是设法建立了我的网站的初稿。
不幸的是,我在尝试实现 Zend\Filter\File\Rename 过滤器的自定义版本时遇到了困难;在这里我总结一下我所做的:
1)在我的名为“库”的模块中,创建了文件
src\Library\Filter\File\Rename.php
namespace Library\Filter\File;
use Traversable;
use Zend\Filter;
use Zend\Filter\Exception;
use Zend\Stdlib\ArrayUtils;
class Rename extends Filter\AbstractFilter {
static $uploadDir = '/srv/default/htdocs/public/uploads/';
public function filter($value) {
do {
$newname = md5(uniqid(time()));
} while(file_exists(self::uploadDir . $newname);
if (rename($value, self::uploadDir . $newname) !== true)
throw new Exception\RuntimeException(sprintf("File '%s' could not be renamed. An error occurred while processing the file.", $value));
return self::uploadDir . $newname;
}
}
如您所见,非常简单。这是模块配置:
模块.config.php
<?php
return array(
'controllers' => array(
// Invokables don't support dependencies
'invokables' => array(
'myFileRename' => 'Library\Filter\File\Rename',
),
));
虽然形式是:
[...]
public function getInputFilterSpecification() {
return array(
'file' => array(
'required' => false,
'filters' => array(
// Custom Renamer
array('name' => 'myFileRename'),
),
)
);
}
}
?>
但这不起作用,因为我总是遇到异常:
Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for myFileRename' in /srv/default/vendor/ZF2/library/Zend/ServiceManager/ServiceManager.php:420
Stack trace:
#0 /srv/default/vendor/ZF2/library/Zend/ServiceManager/AbstractPluginManager.php(108): Zend\ServiceManager\ServiceManager->get('myfilerename', true)
#1 /srv/default/vendor/ZF2/library/Zend/Filter/FilterChain.php(179): Zend\ServiceManager\AbstractPluginManager->get('myfilerename', NULL)
#2 /srv/default/vendor/ZF2/library/Zend/InputFilter/Factory.php(263): Zend\Filter\FilterChain->attachByName('myfilerename', Array)
#3 /srv/default/vendor/ZF2/library/Zend/InputFilter/Factory.php(171): Zend\InputFilter\Factory->populateFilters(Object(Zend\Filter\FilterChain), Array)
#4 /srv/default/vendor/ZF2/library/Zend/InputFilter/Factory.php(237): Zend\InputFilter\Factory->createInput(Array)
#5 /srv/default/vendor/ZF2/library/Zend/Form/Form.php(672) in /srv/default/vendor/ZF2/library/Zend/ServiceManager/ServiceManager.php on line 420
不幸的是,我在整个互联网上找不到任何文章可以帮助我解决这个问题,即使将我的过滤器别名为工厂,我仍然会收到此错误:/ 我该怎么办?