如何从特质回归laravel?

时间:2016-04-20 12:09:03

标签: php laravel laravel-5 laravel-5.1 laravel-5.2

我有控制器:

class UserController extends Controller
{
    public function index(){
        return '1';
    }
}

现在我想要从特征中返回代码:

class UserController extends Controller
{

    use SomeTrait;
    public function index(){
        $this->traitMethod();

        return 2;
    }
}

trait SomeTrait
{
    public function traitMethod(){
        if($this->something == 1){
            return '1';
        }else{
            View::share('somethingElse', 2);
        }
    }
}

在UserController中如果$something = 1,特征应该返回1而其余UserController不应该被执行,我该如何实现?

1 个答案:

答案 0 :(得分:0)

这个:

class UserController extends Controller
{

    use SomeTrait;
    public function index(){
        $this->traitMethod() ? : return 2;
        // if you don't want to return 2, you may return null or something else
        }

        return 2;
    }
}

trait SomeTrait
{
    public function traitMethod(){
        if($this->something == 1){
            return false;
        }else{
            View::share('somethingElse', 2);
        }
    }
}