Skip to content

Instantly share code, notes, and snippets.

@cod3beat
Last active December 16, 2015 16:40
Show Gist options
  • Save cod3beat/5465028 to your computer and use it in GitHub Desktop.
Save cod3beat/5465028 to your computer and use it in GitHub Desktop.
Just a simple experiment on AOP in PHP.
<?php
require 'movement.php';
require 'register_aop.php';
try {
$movement = new Movement;
$movement->walk();
$movement->run();
$movement->crawl(50);
$movement->training();
$movement->training();
$movement->training();
$movement->training();
$movement->training();
$movement->training();
$movement->training();
$movement->training();
$movement->training();
$movement->training();
$movement->training();
$movement->secretFly();
} catch (Exception $e) {
print $e->getMessage();
}
<?php
class Movement
{
protected $power = 10;
public function run($speed = 20)
{
echo "i can run at $speed Km/h";
}
public function walk($speed = 10)
{
echo "i can walk at $speed Km/h";
}
public function stop()
{
echo "i can stop.....";
}
public function crawl($speed = 5)
{
echo "i can crawl at $speed Km/h";
}
public function secretFly()
{
echo "how can you see me fly?";
}
public function training()
{
// Ini aneh, bila menggunakan metode
// $this->power += 10;
// maka aop tidak dijalankan
$newPower = $this->power + 10;
$this->power = $newPower;
return $this->power;
}
public function setPower($value = 10)
{
$this->power = $value;
echo "My power is now " . $this->power . "\n";
}
}
<?php
function dontMove()
{
throw new Exception("This movement is not allowed for you to see\n");
}
function gossip(AopJoinPoint $obj)
{
$activity = $obj->getMethodName();
if (substr($activity, -3, strlen($activity)) == 'ing') {
echo "Wow, he is $activity\n";
} else {
echo "Wow, he can $activity\n";
}
}
function lookMa()
{
echo "Look ma, ";
}
function giveMeABreak()
{
echo "\n";
}
// Memotong alur eksekusi sebuah fungsi
aop_add_before('Movement->secretFly()', 'dontMove');
aop_add_before('Movement->*()', 'gossip');
aop_add_before('Movement->*()', 'lookMa');
aop_add_after('Movement->*()', 'giveMeABreak');
// Mencoba closure -- Ini mengubah argumen yang diberikan kepada
// metode crawl
aop_add_before('Movement->crawl()', function(AopJoinPoint $obj){
$args = $obj->getArguments();
if ($args[0] >= 20) {
echo "You can't crawl at {$args[0]} Km/h. You lied\n";
$obj->setArguments(array(15));
}
});
// Mendeteksi ketika terjadi perubahan pada properti yang dipantau
aop_add_before('write Movement->power', function(AopJoinPoint $obj){
echo $obj->getPropertyName() . ' = ' . $obj->getAssignedValue() . "\n";
});
// Mendeteksi bila kembalian suatu fungsi berada di luar spesifikasi
aop_add_after('Movement->training()', function(AopJoinPoint $obj){
if ($obj->getReturnedValue() > 100) {
echo "You're pushing yourself. Go get some rest\n";
$m = $obj->getObject();
$m->setPower(10);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment