gorgo/golib

共享 PHP 工具库。

0.2.1 2021-01-15 09:09 UTC

This package is auto-updated.

Last update: 2024-09-15 17:11:20 UTC


README

基本的 PHP 工具库。包括基于 XPath 的 Xml Reader 和定义一些类型,如枚举或属性类。

安装

您可以通过 composer 获取此库:composer require gorgo/golib

枚举

基本的 Enum 类提供了一种简单的方法来检查有效的条目。它从 Enum 扩展并定义了一个包含所有可能值的数组,在方法 'getPossibleValueArray()' 中。

use golib\Types\Enum;
class MyEnum extends Enum {
   function getPossibleValueArray(){
        return array('a','b','c');
    }
}

现在只需使用要使用的值来初始化新类。

$myEnum = new MyEnum('b'); // will be accepted
echo $myEnum->geValue();   // 'b'

$exceptionEnum = new MyEnum('g'); // a EnumException will be Trown beause g is not valid

$failEnum = new MyEnum('g',EnumDef::ERROR_MODE_TRIGGER_ERROR); // just triggers an PHP error

ConstEnum

这是一个可以仅通过添加 'const' 来使用的枚举

use golib\Types\ConstEnum;
class MyEnum extends ConstEnum {
  const INTEGER = 1;
  const STRING = 2;
  const ARRAY = 3;
}

用法与 Enum 相同,但您可以使用 'const',这提高了代码风格。

$myEnum = new MyEnum(MyEnum::INTEGER); // of course valid
$value = 2;
$myEnum = new MyEnum($value); // also valid because 2 is defined as ARRAY
$myEnum = new MyEnum(6); // will throw a EnumException
$myEnum = new MyEnum(6, EnumDef::ERROR_MODE_TRIGGER_ERROR); // instead of a exception a error is triggered

属性

Props 类是面向对象的方式来处理作为数组提供的 Content。例如数据库结果。

使用这些的常规方式如下

$query = sprintf("SELECT firstname, lastname, address, age FROM friends ");
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
    echo $row['firstname'];
    echo $row['lastname'];
    echo $row['address'];
    echo $row['age'];
}

这意味着您的代码依赖于数据库设计。如果您稍后访问这些数据,例如在另一个类中,您必须了解数据库结构。如果数据库在某个点重构,这也会很困难。

Props 是一个容器,强制以 OOP 风格访问这些数据

use golib\Props;
class Person extends Props {
    public $firstname = NULL;
    public $lastname = NULL;
    public $adress = NULL;
    public $age = NULL;
}

使用看起来很过度设计,但只是展示了访问数据的不同方式。

$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
    $person = new Person($row);
    echo $person->firstname;
    echo $person->lastname;
    echo $person->adress;
    echo $person->age;
}

所有现代 IDE 都支持代码补全,因此使用 Props 将帮助您获得正确的属性。