I need an example of where to exactly create the file, to write to it, and how to use the functions declared in the trait. I use Laravel Framework 5.4.18
-I have not altered any folder in the framework, everything is where it corresponds-
From already thank you very much.
I have Create a Traits directory in my Http directory with a Trait called BrandsTrait.php
and use it like:
use App\Http\Traits\BrandsTrait;
class YourController extends Controller {
use BrandsTrait;
public function addProduct() {
//$brands = Brand::all();
// $brands = $this->BrandsTrait(); // this is wrong
$brands = $this->brandsAll();
}
}
Here is my BrandsTrait.php
<?php
namespace App\Http\Traits;
use App\Brand;
trait BrandsTrait {
public function brandsAll() {
// Get all the brands from the Brands Table.
$brands = Brand::all();
return $brands;
}
}
Note: Just like a normal function written in a certain namespace, you can use traits as well
Trait description:
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity and avoids the typical problems associated with multiple inheritance and Mixins.
The solution
Make a directory in your App, named Traits
Create your own trait in Traits directory ( file: Sample.php ):
<?php
namespace App\Traits;
trait Sample
{
function testMethod()
{
echo 'test method';
}
}
Then use it in your own controller:
<?php
namespace App\Http\Controllers;
use App\Traits\Sample;
class MyController {
use Sample;
}
Now the MyController class has the testMethod method inside.
You can change the behavior of trait methods by overriding them it in MyController class:
<?php
namespace App\Http\Controllers;
use App\Traits\Sample;
class MyController {
use Sample;
function testMethod()
{
echo 'new test method';
}
}
Let's look at an example trait:
namespace App\Traits;
trait SampleTrait
{
public function addTwoNumbers($a,$b)
{
$c=$a+$b;
echo $c;
dd($this)
}
}
Then in another class, just import the trait and use the function with this as if that function was in the local scope of that class:
<?php
namespace App\ExampleCode;
use App\Traits\SampleTrait;
class JustAClass
{
use SampleTrait;
public function __construct()
{
$this->addTwoNumbers(5,10);
}
}
Related
I have multiple DAO classes (or Repository classes in Laravel jargon).
<?php
namespace App\Repository;
class CompanyRepository extends RepositoryFactory
{
public function getCompany($id)
{
$q = "SELECT COMPANY FROM `COMPANIES` WHERE ID > :id1";
$result = DB::select($q, ["id1" => $id]);
return $result;
}
}
?>
<?php
namespace App\Repository;
class ArticleRepository extends RepositoryFactory
{
public function createArticle($title, $summary)
{
….
}
}
?>
Now I would like for one class to include once all my Repositories (30-40 Repositories) with a class such as RepositoryInclude
<?php
namespace App\Repository;
use App\Repository\ArticleRepository;
use App\Repository\CompanyRepository;
use ….
class RepositoryInclude
{
}
?>
so that from my Controller I could simply:
use App\Repository\RepositoryInclude;
class MYController extends Controller
{
public function __construct(CompanyRepository $companyRepository)
{
$this->companyRepository = $companyRepository;
}
public function index()
{
$companyNameList = $this->companyRepository->getCompany();
}
}
How can I do that? apparently nesting classes with a hierarchy of "use" doesn't work as if I nest a series of "include_once".
PS: I would like to use common PHP language techniques which I can reuse in the future and no Laravel "hacks", expecially if they involve command line commands which I'm avoiding as much as possible.
I am writing system for players where I use Laravel freamwork (just for learn) and I have question for more experience developer. I have one function which return me some data to view. I use this function in 3 controllers (but i copy and paste this function to each Controller files) and can I just put this function in one file and then use it in these 3 controllers? How can I use the same function in diffrent controller without copy and past?
You can also use Traits to share methods, however, traits are more usually for describing characteristics and types.
You should create a utility class, or use consider an abstract controller class if this is desired.
You can create Base Controller:
<?php
namespace App\Http\Controllers;
class BaseController
{
protected $playersRepository;
public function __construct(PlayersRepository $playersRepository)
{
$this->playersRepository = $playersRepository;
}
}
Which is injected with a repository object:
<?php
namespace App\Http\Controllers;
class PlayersRepository
{
public function getPlayers()
{
return Player::all();
}
}
Which has a common method, that can be used in more than one extended controller:
Games
<?php
namespace App\Http\Controllers;
class Games extends BaseController
{
public function index()
{
return view('games', ['players' => $this->playersRepository->getPlayers()]);
}
}
Matches
<?php
namespace App\Http\Controllers;
class Matches extends BaseController
{
public function show()
{
return view('matches', [
'matches' => $matches,
'players' => $this->playersRepository->getPlayers()
]);
}
}
Create module (util) or override main Controller class.
I'm new to Traits, but I have a lot of code that is repeating in my functions, and I want to use Traits to make the code less messy. I have made a Traits directory in my Http directory with a Trait called BrandsTrait.php. And all it does is call on all Brands. But when I try to call BrandsTrait in my Products Controller, like this:
use App\Http\Traits\BrandsTrait;
class ProductsController extends Controller {
use BrandsTrait;
public function addProduct() {
//$brands = Brand::all();
$brands = $this->BrandsTrait();
return view('admin.product.add', compact('brands'));
}
}
it gives me an error saying Method [BrandsTrait] does not exist. Am I suppose to initialize something, or call it differently?
Here is my BrandsTrait.php
<?php
namespace App\Http\Traits;
use App\Brand;
trait BrandsTrait {
public function brandsAll() {
// Get all the brands from the Brands Table.
Brand::all();
}
}
Think of traits like defining a section of your class in a different place which can be shared by many classes. By placing use BrandsTrait in your class it has that section.
What you want to write is
$brands = $this->brandsAll();
That is the name of the method in your trait.
Also - don't forget to add a return to your brandsAll method!
use App\Http\Traits\BrandsTrait;
class ProductsController extends Controller {
use BrandsTrait;
public function addProduct() {
//$brands = Brand::all();
$brands = $this->brandsAll();
return view('admin.product.add', compact('brands'));
}
}
I'm trying to set up PSR-4 within a new Laravel 4 application, but I'm getting some troubles achieving what I want when it comes to build controllers.
Here's what I have now :
namespace MyApp\Controllers\Domain;
class DomainController extends \BaseController {
public $layout = 'layouts.default';
public function home() {
$this->layout->content = \View::make('domain.home');
}
}
I'm not so fond of using \View, \Config, \Whatever to use Laravel's classes. So I was wondering if I could put a use Illuminate\View; to be able to use View::make without putting a \.
Unfortunately, while doing this, I'm getting the following error : Class 'Illuminate\View' not found.
Could somebody help with this please ?
The problem in your case is that View is not located in Illuminate namespace but in Illuminate\View namespace, so correct import would be not:
use Illuminate\View;
but
use Illuminate\View\View;
You can look at http://laravel.com/api/4.2/ to find out which namespace is correct for class you want to use
Assuming BaseController.php has a namespace of MyApp\Controllers\Domain
namespace MyApp\Controllers\Domain;
use View;
class DomainController extends BaseController {
public $layout = 'layouts.default';
public function home() {
$this->layout->content = View::make('domain.home');
}
}
If BaseController.php has other namespace, i.e MyApp\Controllers
namespace MyApp\Controllers\Domain;
use MyApp\Controllers\BaseController;
use View;
class DomainController extends BaseController {
public $layout = 'layouts.default';
public function home() {
$this->layout->content = View::make('domain.home');
}
}
If, for instance, you controller needs to use another base class from Laravel, lets say Config.
namespace MyApp\Controllers\Domain;
use MyApp\Controllers\BaseController;
use View;
use Config;
class DomainController extends BaseController {
public $layout = 'layouts.default';
public function home() {
$this->layout->content = View::make('domain.home')->withName(Config::get('site.name'));
}
}
The use of View::make() takes advantage of the Laravel facades. To properly reference the facade, instead of directly referencing the class that gets resolved out of the iOC container, I would use the following:
use Illuminate\Support\Facades\View;
This will reference the View facade that is being used when calling View::make()
I have a base controller as follows
<?php
use Phalcon\Mvc\Controller;
class ControllerBase extends Controller {
public function initialize() {
}
// wrapper function for debug purposes.
public function pr($data = null) {
echo '<pre>';
print_r($data);
echo '</pre>';
}
}
and a users controller as follows
<?php
use Phalcon\Mvc\Model\Criteria;
use Phalcon\Paginator\Adapter\Model as Paginator;
use Phalcon\Mvc\View;
class UsersController extends ControllerBase {
public function initialize() {
// initialize parent, here ControllerBase.
parent::initialize();
}
public function loginAction() {
// disable the main layout.
$this->view->disableLevel(View::LEVEL_MAIN_LAYOUT);
// disable the controller layout.
$this->view->disableLevel(View::LEVEL_LAYOUT);
}
.
.
.
.
other functions...
}
i was wondering if i could call all the required phalcon classes in base controller and extend then to all the child classes so that i dont need to call them individually on each controller.
in otherwords, can i add the below code
use Phalcon\Mvc\Model\Criteria;
use Phalcon\Paginator\Adapter\Model as Paginator;
use Phalcon\Mvc\View;
only in the base controller and acces them in other controllers. I tried putting them base controller but it gave error : Class not found.
Is this the right way or is there something wrong in my approach...please help.
If I understand your question correctly the answer is NO.
Namespaces are language feature and works this way. The use Phalcon\Mvc\Model\Criteria only declares that you'll use Criteria class from Phalcon\Mvc\Model\ namespace. So in your code you can write new Criteria() to create object instead of using its' full name new \Phalcon\Mvc\Model\Criteria().
You must declare each class in every file which instantiates object of that class so autoloader will know in which file given class exists.