cloudson/gandalf

此包最新版本(0.7.0)没有可用的许可证信息。

0.7.0 2014-01-26 00:12 UTC

This package is not auto-updated.

Last update: 2024-09-24 05:19:05 UTC


README

Gandalf 是一个处理函数的(疯狂)php 库。

在哪里使用?

  • php5.4+
  • 勇敢的人在哪里

为什么使用?

众所周知,我们的首选语言有对象半开放性,我的意思是,我们可以在执行时间定义实例字段,如下所示

<?php

class Baggin
{

}

$bilbo = new Baggin;
$bilbo->hasRing =  true; 

var_dump($bilbo->hasRing); // true

但我们不能像函数式编程语言(javascript、ruby...)那样插入方法

<?php

class Elf
{

}

$legolas = new Elf;
$legolas->attack = function () {
    echo 'Goooo!';
};

$legolas->attack(); // Fatal error: Call to undefined method Elf::attack()

如何使用它

使用我们的 trait

<?php

class Elf
{
    use Gandalf\Entity\Caller;
}

$legolas = new Elf;
$legolas->attack = function () {
    echo 'Goooo!';
};

$legolas->attack(); // Goooo! =) 

定义函数模式

在 Doctrine\ORM 中存在一个用于搜索实体的动态方法

<?php

$repository->findOneByName('bar');
$repository->findByPlace('Middle earth');

使用 Gandalf 你可以编写类似的方法,使用正则表达式模式,如下所示

<?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'"

注意 $this->_1 是一个正则表达式组变量。你也可以使用变量 $this->matches[1]

重要:$this 不是当前上下文

<?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']"

创建快捷方式

很多时候,我们需要编写复合调用,如下

<?php
return str_replace(' ', '-', strtolower(trim($foo)));

使用 Gandalf 你可以编写这样

<?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

为什么在使用此库在生产环境中之前应该小心。

  • Galdalf 是一个巫师,巫师会施展魔法。因此,此库使用了大量的 PHP 魔法方法。Galdalf 的性能可能成为您应用程序的问题。
  • 目前,创建一个无效名称的函数是可能的。例如,正则表达式 '/[a-z]#[a-z]/' 是可接受的,但你永远不会调用 $foo->a#a()。

并且...

如果您想讨论此项目,请通过 twittercloudson@outlook.com 联系我。那会很棒!

Bitdeli Badge