Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load traits via composer autoload

I have tried add my traits folder to composer custom autoload but this is doesn't work and returns an error. So is this possible autoload traits via composer? Many thanks for any answer.

My trait:

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;
  }
}

My class:

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');

  ...
 }
}

My composer file:

{    
    "autoload": {
        "psr-0": {
            "User": "Validation"
        }
    }
}
like image 470
Andrii Tarykin Avatar asked Mar 17 '14 15:03

Andrii Tarykin


1 Answers

I tested back and forth some time now with PHP 5.5.3, and while I have to report that during testing things looked broken (more likely due to me producing a VM with that version on short notice, with no settings and the wronk keyboard layout), in the end I cannot reproduce the error. I'd say that autoloading for traits works as advertised.

Now here is what I did:

In the home directory:

composer.json

{
    "autoload": {"psr-0":{"User":"src"}}
}

Also:

test.php

<?php

require "vendor/autoload.php";

class Auth {
    use User;
}

new Auth;

In the directory src:

src/User.php

<?php

trait User {}

Running composer install creates vendor/composer/autoload_namespaces.php with this array entry:

'User' => array($baseDir . '/src'),

And executing the testscript works for me.

Note that it is important to have the naming of the files correct. They have to match exactly according to PSR-0 rules (or PSR-4 if you prefer using namespaces), including case sensitive correct filenames.

If you have a trait named "User", and you define PSR-0 autoloading like "User": "Validation", the expected situation would be that the following file exists: Validation/User.php with the content:

<?php

trait User {
    // stuff here
}

This trait will then be able to be autoloaded after running at least once composer install.

like image 159
Sven Avatar answered Oct 31 '22 15:10

Sven