Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a trait method with alias

I'm trying to place a trait inside a class called Page. I also need to rename a trait function so that it doesn't clash with an existing class function. I thought I did all this successfully however I get an error that points to the wrong location?!

Call to undefined function App\Pages\Models\myTraitDefaultScope()

I've also tried: MyTrait\defaultScope($query) instead of trying to rename the conflicting function. But I then get the following error:

Call to undefined function App\MyTrait\defaultScope()

Below is the trait and class contained in separate files.

<?php
namespace App;

use Illuminate\Support\Facades\Auth;

trait MyTrait{
    public function defaultScope($query){
        return $query->where('active', '1')
    }
}

.

<?php namespace Modules\Pages\Models;
use Illuminate\Database\Eloquent\Model;
use App\MyTrait;

class Page extends Model {

    use MyTrait{
        MyTrait::defaultScope as myTraitDefaultScope;
    }

    public function defaultScope($query){
        return myTraitDefaultScope($query);
    }
}

I'm not all that awesome at this so please don't shoot if I've got something badly wrong :)

like image 794
Jammer Avatar asked Dec 18 '15 20:12

Jammer


2 Answers

When you 'use' a trait in your class, the class inherits all the methods and properties of the trait, like if it was extending an abstract class or an interface

So, this method of MyTrait:

public function defaultScope($query){
    return $query->where('active', '1')
}

will be inherited by your Page class

As you have aliased this method as: myTraitDefaultScope, to call the method you should call it in the same way you would call every other method of the Page class:

public function defaultScope($query){

    //call the method of the class
    return $this->myTraitDefaultScope($query);
}
like image 200
Moppo Avatar answered Oct 07 '22 18:10

Moppo


As you're using trait. So it points to the current or parent class. Thus, calling any method should be like $this->method($params); syntax.

like image 27
ssi-anik Avatar answered Oct 07 '22 18:10

ssi-anik