Where to place traits in Laravel 5?
I am using Laravel 5 and I am confused about where to place traits files in the Laravel 5 directory structure. Should they exist in public, resources or any other directory?
Solution 1:
In terms of placement you should treat traits like classes. That means put them inside the app
directory. Where you place your traits in there depends on your preference and on the actual purpose of the trait.
Important is that you adjust the namespace of the trait to the directory structure. For example if your trait has something to do with your controllers and you decide to put it inside the app/Http/Controllers
folder, then make sure it has the correct namespace, which would be:
namespace App\Http\Controllers;
Solution 2:
I prefer creating a directory in app called Traits. This will enhance the readability and maintainability of code base .
Example:
namespace App\Traits;
use Exception;
use Illuminate\Http\Request;
trait myTrait {
//your code here
}
Solution 3:
You can place trait any where you want. But in terms of placement you should adjust the namespace of the trait to the directory structure.
For example : You want to create a Traits directory Traits >> SayHello.php
.
app >> Http >> Controllers >> Traits >> SayHello.php
<?php
namespace App\Http\Controllers\Traits;
trait SayHello{
public function hello()
{
return "Hello";
}
}
app >> Http >> Controllers >> HomeController.php
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Controllers\Traits\SayHello;
class HomeController extends Controller {
use SayHello;
public function index()
{
// Called SayHello trait hello method
return $this->hello();
}
}
Solution 4:
Storing Traits
For convenience, create a directory under app
called Traits
, and placed my custom PHP files there. Each file uses the name of the Trait for logical correlation. By using a namespace of App/Traits
in each file the Framework was able to locate my files when I use
them in another file.
Sample Usage Code:
<?php
namespace AppJobs;
use App/Jobs/Job;
use App/Traits/ExampleCode;
/**
* brief Example code using a Trait in a Laravel "Job"
*/
class AdminLoginJob extends Job implements SelfHandling
{
use ExampleCode;
/**
* Call trait to print something. Note the use of "$this".
*
* @return void
*/
public function __construct()
{
$this->printThis();
}
/**
* Do more stuff here.
*
* @return void
*/
public function handle()
{
// never gets called in this example.
}
}