SaidbakR
SaidbakR

Reputation: 13544

Laravel controller use trait that uses another used trait

I have a controller that uses two traits, CavityTools and OperationTools

class OperationController extends Controller
{

    use \App\Traits\CavityTools;
    use \App\Traits\OperationTools;

However, the second trait OperationTools usingCavityTools`:

trait OperationTools {
    use \App\Traits\CavityTools;

So when I try to use a method of OperationTools from any controller's method such as $this->getProduction(), I have got an error tells about a method in the CavityTools that it is not applied due to collision:

Trait method cavityPerformanceBetweenTimes has not been applied, because there are collisions with other trait methods on App\Http\Controllers\OperationController

I have tried to to alias the second trait, use \App\Traits\OperationTools as OpTs; but it generate parse error:

Parse error: syntax error, unexpected 'as' (T_AS), expecting ',' or ';' or '{'

How could I solve this issue?

Upvotes: 1

Views: 1795

Answers (2)

Kyslik
Kyslik

Reputation: 8385

Just use the OperationTools trait since CavityTools are already used.

Example code:

<?php


trait A {
    function a() {
        echo "a trait\n";
    }
}

trait B {
    use A;
    function b() {
        echo "b trait\n";
    }

    function a() {
        echo "a fcn from trait B\n";
    }
}

trait C {
    use B;
    function a() {
        echo "a fcn from C trait\n";
    }

    function b() {
        echo "b fcn from C trait\n";
    }
}


class AClass {
    use A;
}

$classA = new AClass;
$classA->a();
// $classB->b(); // will throw up


class BClass {
    use B;
}

$classB = new BClass;
$classB->a();
$classB->b();

class CClass {
    use C;
}

$classC = new CClass;
$classC->a();
$classC->b();

// output

a trait
a fcn from trait B
b trait
a fcn from C trait
b fcn from C trait

Upvotes: 2

Kuldeep Singh Rathore
Kuldeep Singh Rathore

Reputation: 126

This is because there are same functions in both traits. To avoid that you will have to use "InsteadOf" in your current class.

Reference - Collisions with other trait methods

Upvotes: 1

Related Questions