And*_*kin 10 php traits autoload composer-php
我已经尝试将我的traits文件夹添加到composer自定义自动加载,但这不起作用并返回错误.那么这可能是通过作曲家自动加载的特征吗?非常感谢任何答案.
我的特点:
trait User
{
public function is_email_unique($email)
{
return $this->User->get_one_by_email($email) ? FALSE : TRUE;
}
public function is_username_unique($username)
{
return $this->User->get_one_by_username($username) ? FALSE : TRUE;
}
}
Run Code Online (Sandbox Code Playgroud)
我的课:
class Auth extends MY_Controller
{
// Implement trait in class
use User;
public function __contstruct()
{
parent::__contstruct();
}
public function register()
{
if ($this->input->is_post()) {
// load validation library
$this->load->library('form_validation');
//set validation rules
$this->form_validation->set_rules('username', "Username", 'required|callback_username_check');
// There I use my trait method callback_is_email_unique
$this->form_validation->set_rules('email', "Email", 'required|valid_email|callback_is_email_unique');
$this->form_validation->set_rules('password', "Password", 'required|matches[confirm_password]|min_length[6]');
$this->form_validation->set_rules('confirm_password', "Confirm password", 'required');
...
}
}
Run Code Online (Sandbox Code Playgroud)
我的作曲家档案:
{
"autoload": {
"psr-0": {
"User": "Validation"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我现在用PHP 5.5.3来回测试了一段时间,虽然我必须报告在测试期间看起来很糟糕(更可能是因为我在短时间内生成了具有该版本的VM,没有设置和wronk键盘布局),到最后我无法重现错误.我会说特征的自动加载与宣传的一样.
现在这就是我所做的:
在主目录中:
composer.json
{
"autoload": {"psr-0":{"User":"src"}}
}
Run Code Online (Sandbox Code Playgroud)
也:
test.php
<?php
require "vendor/autoload.php";
class Auth {
use User;
}
new Auth;
Run Code Online (Sandbox Code Playgroud)
在目录中src:
src/User.php
<?php
trait User {}
Run Code Online (Sandbox Code Playgroud)
使用此数组条目composer install创建运行vendor/composer/autoload_namespaces.php:
'User' => array($baseDir . '/src'),
Run Code Online (Sandbox Code Playgroud)
执行测试脚本对我有用.
请注意,正确命名文件很重要.它们必须完全符合PSR-0规则(如果您更喜欢使用名称空间,则为PSR-4),包括区分大小写的正确文件名.
如果您有一个名为"User"的特征,并且您定义了PSR-0自动加载,如"User":"Validation",则预期的情况是存在以下文件:Validation/User.php内容:
<?php
trait User {
// stuff here
}
Run Code Online (Sandbox Code Playgroud)
然后,在运行至少一次之后,该特征将能够被自动加载composer install.