phramz / commons
此包已被废弃且不再维护。没有建议的替代包。
实用库
v1.0.3
2014-01-25 21:52 UTC
Requires
- php: >=5.3
This package is not auto-updated.
Last update: 2023-08-28 06:09:48 UTC
README
Commons 是一个 php 库,包含了一些实用的工具,可以简化你的日常编码工作。
安装
如果你使用 composer,安装非常简单!
编辑你的 composer.json
"require": { "phramz/commons": "*" }
或者通过命令行
php composer.phar require phramz/commons
示例
想象一下...
<?php use Phramz\Commons\Property\PropertyUtils; class Contact { private $email = 'info@phramz.com'; private $phone = '123' public function getEmail() { return $this->email; } public function setEmail($email) { $this->email = $email; } public function getPhone() { return $this->phone; } public function setPhone($phone) { $this->phone = $phone; } } class User { private $name = 'foo'; private $contact = null; public function __construct() { $this->contact = new Contact(); } public function getName() { return $this->name; } public function setName($name) { $this->name = $name; } public function getContact() { return $this->contact; } public function setContact(Contact $contact) { $this->contact = $contact; } } // get an instance of our User class $example = new User();
现在,你可能想访问私有成员 name
// get an instance of PropertyUtils $propertyUtils = new PropertyUtils(); $propertyUtils->getProperty('name', $example); // will return 'foo'
哇!并不太令人兴奋,只要你能直接调用 getName()
,对吧!但如果你有一个任意对象,你不知道是否有公共方法 getName()
,或者 name
可能只是一个公共成员,因此不需要 getter?该对象可能甚至没有名为 name
的成员并且实现了 ArrayAccess
?getProperty()
方法可以处理所有这些情况。
同样,你也可以将 name
设置为另一个值
// get an instance of PropertyUtils $propertyUtils = new PropertyUtils(); $propertyUtils->setProperty('name', 'bar', $example); $propertyUtils->getProperty('name', $example); // will now return 'bar' ... as well as $example->getName(); // ... will also return 'bar'
如果你需要,你也可以通过使用路径分隔符 .
来访问任何深度的嵌套成员,例如 email
// get an instance of PropertyUtils $propertyUtils = new PropertyUtils(); $propertyUtils->getProperty('contact.email', $example); // will return 'info@phramz.com'
你需要处理数组吗?没问题
// if our User-object were an array it would look like this $example = array( 'name' => 'foo', 'contact' => array( 'email' => 'info@phramz.com', 'phone' => '123' ) ); // get an instance of PropertyUtils $propertyUtils = new PropertyUtils(); $propertyUtils->getProperty('name', $example); // will still return 'foo' $propertyUtils->getProperty('contact.email', $example); // will still return 'info@phramz.com'
如果你正在处理数组,会有一个区别,因为这些值不是对象那样的引用。所以,如果我们想设置一个新值给一个成员,我们需要保存处理过的数组。
// get an instance of PropertyUtils $propertyUtils = new PropertyUtils(); // setProperty() will return the manipulated array, so we write it back to $example $example = $propertyUtils->setProperty('name', 'bar', $example); $propertyUtils->getProperty('name', $example); // will return 'bar' ... as well as $example->getName(); // ... will also return 'bar'
就这样!我希望这个软件片段能有所帮助!祝你好运!