PHP code example of blackcube / magic-compose

1. Go to this page and download the library: Download blackcube/magic-compose library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

blackcube / magic-compose example snippets


class MyClass {
    use TraitA, TraitB; // TraitB::__get shadows TraitA::__get
}

class MyClass {
    use MagicComposeTrait, TraitA, TraitB;
}

trait TraitA {
    #[MagicGetter]
    protected function getFromA(string $name): mixed {
        if ($name === 'foo') return 'from A';
        throw new MagicNotHandledException();
    }
}

trait TraitB {
    #[MagicGetter(priority: Priority::HIGH)]
    protected function getFromB(string $name): mixed {
        if ($name === 'bar') return 'from B';
        throw new MagicNotHandledException();
    }
}

$obj = new MyClass();
$obj->foo; // 'from A'
$obj->bar; // 'from B'

use Blackcube\MagicCompose\Attributes\Priority;

#[MagicGetter(priority: Priority::HIGH)]  // 90 - runs first
#[MagicGetter(priority: Priority::NORMAL)] // 50 - default
#[MagicGetter(priority: Priority::LOW)]    // 10 - runs last

trait AuditTrait {
    use MagicComposeMethodsBaseTrait;

    #[MagicExtend(method: 'save')]
    protected function auditSave(): bool {
        $this->log('before save');
        $result = $this->next(); // call parent::save() or next handler
        $this->log('after save');
        return $result;
    }
}

use Yiisoft\ActiveRecord\ActiveRecord;
use Blackcube\MagicCompose\MagicComposeActiveRecordTrait;

class User extends ActiveRecord {
    use MagicComposeActiveRecordTrait;
    use SomeCustomTrait;
}