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'));
}
}
Related
public function create() { $Gallery= GalleryModel::all(); return view('admin.gallery',compact('Gallery')); }
public function video() { $Video= VideoModel::all(); return view('admin.video',compact('Video')); }
public function team() { $Team = TeamModel::all(); return view('admin.team',compact('Team')); }
Is where is any way to make single method for different pages
There are many of ways to do that. The general idea is to use Traits.
// ControllerTrait.php
trait ControllerTrait {
// Here you include all yor controller's methods
}
Then, in every controller you use your trait
// YourController.php
class YourController extends Controller {
use ControllerTrait;
// The rest of your controller's code
}
You can even go further if you consider classes inheritance:
You could create a base controller like this:
// MyBaseController.php
class BaseController extends Controller {
use ControllerTrait; // <= you can mix the strategies for more power
// All your BaseController's methods
}
An then let your controllers extend from the base one instead:
// YourController.php
class YourController extends BaseController {
//
}
You could, in the end, just edit you BaseController and your ControllerTrait and ease your life a lot.
NOTE: Editted because you werer talking about Controllers and I was thinking about Models, but you can surely use the same principle for managing your models.
NOTE 2: Traits are better for methods that really will work as default for all controllers, and keep in the BaseModel those that will need to be customized in any of the inheriting controllers. For example:
// MyBaseController.php
class BaseController extends Controller {
protected function a($request) {
//
}
}
// YourController.php
class YourController extends BaseController {
protected function a($request) {
$request = $modifiedRequest; // You can modify the inputs
parent::a($request); // <== Execute the parent method;
}
}
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);
}
}
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 have been facing a problem of not able to use the model inside the controller in the new laravel framework version 5. i created the model using the artisan command
"php artisan make:model Authentication" and it created the model successfully inside the app folder, after that i have created a small function test in it, and my model code looks like this.
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function test(){
echo "This is a test function";
}
}
Now i have no idea, that how shall i call the function test() of model to my controller , Any help would be appreciated, Thanks in advance.
A quick and dirty way to run that function and see the output would be to edit app\Http\routes.php and add:
use App\Authentication;
Route::get('authentication/test', function(){
$auth = new Authentication();
return $auth->test();
});
Then visit your site and go to this path: /authentication/test
The first argument to Route::get() sets the path and the second argument says what to do when that path is called.
If you wanted to take this further, I would recommend creating a controller and replacing that anonymous function with a reference to a method on the controller. In this case, you would change app\Http\Routes.php by instead adding:
Route::get('authentication/test', 'AuthenticationController#test');
And then use artisan to make a controller called AuthenticationController or create app\Http\Controllers\AuthenticationController.php and edit it like so:
<?php namespace App\Http\Controllers;
use App\Authentication;
class AuthenticationController extends Controller {
public function test()
{
$auth = new Authentication();
return $auth->test();
}
}
Again, you can see the results by going to /authentication/test on your Laravel site.
Use scope before method name
<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
class Mainmenu extends Model
{
public function scopeLeftmenu() {
return DB::table('mainmenus')->where(['menu_type'=>'leftmenu', menu_publish'=>1])->orderBy('menu_sort', 'ASC')->get();
}
}
above code i tried to access certain purpose to call databse of left menu
than we can easy call it in Controller
<?php
Mainmenu::Leftmenu();
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function scopeTest(){
echo "This is a test function";
}
}
Just prefix test() with scope. This will become scopeTest().
Now you can call it from anywhere like Authentication::Test().
For me the fix was to set the function as static:
public static function test() {..}
And then call it in the controller directly:
Authentication::test()
You can call your model function in controller like
$value = Authentication::test();
var_dump($value);
simply you can make it static
public static function test(){
....
}
then you can call it like that
Authentication::test();
1) First, make sure your Model is inside a Models Folder
2) Then supposing you have a model called Property inside which you have a method called returnCountries.
public function returnCountries(){
$countries = Property::returnCountries();
}
of course, in your case, replace Property by the name of your Model, and returnCountries by the name if your function, which is Test
and in the Model you write that function requesting the countries
so in your Model, place a:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function test(){
return $test = "This is a test function";
}
}
and this is what your Controller will be getting
You should create an object of the model in your controller function then you can model functions inside your controller as:
In Model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Authentication extends Model {
protected $table="canteens";
public function test(){
return "This is a test function"; // you should return response of model function not echo on function calling.
}
}
In Controller:
namespace App\Http\Controllers;
class TestController extends Controller
{
// this variable is used to store authenticationModel object
protected $authenticationModel;
public function __construct(Request $request)
{
parent::__construct($request);
$this->authenticationModel= new \App\Authentication();
}
public function demo(){
echo $this->authenticationModel->test();
}
}
Output:
This is a test function
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.