Wallogit.com
2017 © Pedro Peláez
Gandalf is a (crazy) php library that handles functions., (*1)
As we know, our prefer language has object semi opened, I mean, we can define instance fields in execution time, see below:, (*2)
<?php
class Baggin
{
}
$bilbo = new Baggin;
$bilbo->hasRing = true;
var_dump($bilbo->hasRing); // true
But, we couldn't insert methods as functional programming languages (javascript, ruby ...), (*3)
<?php
class Elf
{
}
$legolas = new Elf;
$legolas->attack = function () {
echo 'Goooo!';
};
$legolas->attack(); // Fatal error: Call to undefined method Elf::attack()
Use our trait:, (*4)
<?php
class Elf
{
use Gandalf\Entity\Caller;
}
$legolas = new Elf;
$legolas->attack = function () {
echo 'Goooo!';
};
$legolas->attack(); // Goooo! =)
In Doctrine\ORM exists a method dynamic for search entities:, (*5)
<?php
$repository->findOneByName('bar');
$repository->findByPlace('Middle earth');
with Gandalf you can write similar methods that use regex pattern, see below:, (*6)
<?php
$legolas = new Elf;
$legolas->def('findBy([A-Z][a-z]+)', function($value){
return "Find by {$this->_1}";
});
$legolas->findByName('bilbo'); // "return 'Find by Name'"
note that $this->_1 is a group var regex. You could too use var $this->matches[1]., (*7)
Important: $this don't is the current context, (*8)
<?php
$legolas = new Elf;
$legolas->def('find(One){0,1}By([A-Z][a-z]+)', function($value){
var_dump($this->matches);
});
$legolas->findByName('bilbo'); // "['findByName', null, 'Name']"
$legolas->findOneByFamily('bilbo'); // "['findOneByFamily', null, 'Family']"
Many times, we need write compound calls like, (*9)
<?php
return str_replace(' ', '-', strtolower(trim($foo)));
with Gandalf you can write this, (*10)
<?php
$foo = new Elf;
$foo->short('getSlug', [
['trim', ":param1"],
['strtolower', ":return1"],
['str_replace',' ', '-',":return2"],
]);
$foo->getSlug('How use crazy Gandalf lib!'); // how-use-crazy-gandalf-lib
Contact-me on twitter or cloudson@outlook.com if you want talk about this project. It would be awesome!, (*11)