PHP: Trait - Manual

`I want to make flexible module that contains different functionality and I want to combine this but using the same methods:

<?php
class Brain {
    public function ask($q) { // Trate the question return 'Some response';
    }
}

trait BrainLogger {
    public function ask($q) { log('Received a question: ' . $q);
        return parent::ask();
    }
}
trait BrainMad {
    public function ask($q) {
        if(rand(0,1) == 1) {
               return parent::ask($q);      
        } else {
               return 'I don't wanna talk with you.';
        }
    }
}
?>

In some part of my application I want to use different combinations of that functionality so if I want one brain instance:

<?php
$brain = new Brain;
$brain->ask('what we gonna do tonight?');
?>

If I want log all received questions:

<?php
class NiceBrain extends Brain {
    use BrainLog;
}
$brain = new Brain;
$brain->ask('what we gonna do tonight?'); // Will log
?>

If I want to extend more I need to make a cascade of classes:
<?php
class NiceBrain extends Brain {
    use BrainLog;
}
class CrazyBrain extends NiceBrain {
    use BrainMad;
}
$brain = new CrazyBrain;
$brain->ask('What we gonna do tonight?');
// Will output  'I don't wanna talk with you.' or normal response
// but logging only in case BrainMad has a good mood
?>

Because using of multiple traits will call only one selected in section "use Trait;".`


Original url: Access
Created at: 2018-10-30 13:56:00
Category: default
Tags: none

请先后发表评论
  • 最新评论
  • 总共0条评论