学习笔记(二)
一.Zend\Authentication
Zend\Authentication只涉及认证(authentication),不涉及授权(authorization)。认证松散地定义为,决定一个实体实际是不是它所声称的(例如,鉴定(identification,或识别、身份证明)),基于证书的一些集(credentials,凭证、证件、证书)。
use Zend\Authentication\Adapter\AdapterInterface;
class My\Auth\Adapter implements AdapterInterface
{
/**
* 为认证设置username和password
*
* @return void
*/
public function __construct($username, $password)
{
// ...
}
/**
* 执行一个认证企图
*
* @return \Zend\Authentication\Result
* @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface
* If authentication cannot be performed
*/
public function authenticate()
{
// ...
}
}
|
\Zend\Authentication\Result
- isValid()- 返回TRUE,如果和只有结果代表一个成功的认证企图时。
- getCode()- 返回一个Zend\Authentication\Result常量标识,决定认证失败类型或者成功是否发生。这可以用在开发者希望分布在几个认证结果类型的情况下。例如允许开发者维护详细的认证结果统计。该特性的另一个使用是为了可用性的原因,提供具体的、自定义消息给用户,尽管开发者被鼓励考虑提供这种细节的原因到用户的风险,代替一般认证失败消息。更多信息,见下面注释。
- getIdentity()- 返回认证企图的身份。
- getMessages()- 返回一个消息数组,不管一个失败的认证企图。
身份持久性
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Storage\Session as SessionStorage;
$auth = new AuthenticationService();
// 使用'someNamespace'作为session的命名空间,而不是'Zend_Auth'
$auth->setStorage(new SessionStorage('someNamespace'));
/**
* @todo 建立auth适配器, $authAdapter
*/
// 认证,保存结果,在成功时持久化身份
$result = $auth->authenticate($authAdapter);
|
数据库表认证
Zend\Authentication\Adapter\DbTable构造器需要一个Zend\Db\Adapter\Adapter实例,充当认证适配器实例绑定到的数据库连接。首先应该创建数据库连接。
use Zend\Db\Adapter\Adapter as DbAdapter;
// 创建一个SQLite 数据库连接
$dbAdapter = new DbAdapter(array(
'driver' => 'Pdo_Sqlite',
'database' => 'path/to/sqlite.db'
));
// 建立一个简单的表创建查询
$sqlCreate = 'CREATE TABLE [users] ('
. '[id] INTEGER NOT NULL PRIMARY KEY, '
. '[username] VARCHAR(50) UNIQUE NOT NULL, '
. '[password] VARCHAR(32) NULL, '
. '[real_name] VARCHAR(150) NULL)';
// 创建认证证书表
$dbAdapter->query($sqlCreate);
// 建立一个查询插入一行,为了认证可以成功
$sqlInsert = "INSERT INTO users (username, password, real_name) "
. "VALUES ('my_username', 'my_password', 'My Real Name')";
// 插入数据
$dbAdapter->query($sqlInsert);
|
use Zend\Authentication\Adapter\DbTable as AuthAdapter;
// 用构造器参数配置实例...
$authAdapter = new AuthAdapter($dbAdapter,
'users',
'username',
'password');
// ...或者用setter方法配置实例
$authAdapter = new AuthAdapter($dbAdapter);
$authAdapter
->setTableName('users')
->setIdentityColumn('username')
->setCredentialColumn('password')
二.Zend\Db
创建适配器:
$adapter = new Zend\Db\Adapter\Adapter(array( 'driver' => 'Mysqli', 'database' => 'zend_db_example', 'username' => 'developer', 'password' => 'developer-password' ));
查询预处理:$adapter->query('SELECT * FROM `artist` WHERE `id` = ?', array(5));
查询执行: $adapter->query('ALTER TABLE ADD INDEX(`foo_index`) ON (`foo_column`)', Adapter::QUERY_MODE_EXECUTE);
创建语句: $statement = $adapter->createStatement($sql, $optionalParameters); $result = $statement->execute();
Zend\Db\ResultSet 必须实现 Zend\Db\ResultSet\ResultSetInterface,Zend\Db 所有返回 ResultSet 的子组件将假定一个 ResultSetInterface 的实例应被返回。
use Zend\Db\Adapter\Driver\ResultInterface; use Zend\Db\ResultSet\ResultSet; $stmt = $driver->createStatement('SELECT * FROM users'); $stmt->prepare(); $result = $stmt->execute($parameters); if ($result instanceof ResultInterface && $result->isQueryResult()) { $resultSet = new ResultSet; $resultSet->initialize($result); foreach ($resultSet as $row) { echo $row->my_column . PHP_EOL; } }
有四个主要对象可供开发者交互或是创建查询,Zend\Db\Sql\Select、Insert、Update 和 Delete
预处理:
use Zend\Db\Sql\Sql; $sql = new Sql($adapter); $select = $sql->select(); $select->from('foo'); $select->where(array('id' => 2)); $statement = $sql->prepareStatementForSqlObject($select); $results = $statement->execute();
执行:
use Zend\Db\Sql\Sql; $sql = new Sql($adapter); $select = $sql->select(); $select->from('foo'); $select->where(array('id' => 2)); $selectString = $sql->getSqlStringForSqlObject($select); $results = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);
Zend\Db\Sql\Select 主要功能是为创建平台特定的 SQL SELECT 查询提出一个统一的API
use Zend\Db\Sql\Select; $select = new Select(); // or, to produce a $select bound to a specific table $select = new Select('foo');
from表
$select->from(array('t' => 'table'));
column列
$select->columns(array('foo', 'bar'));
join连接
$select->from(array('f' => 'foo')) // 基础表
->join(array('b' => 'bar'), // 使用别名联合表 'f.foo_id = b.foo_id'); // join 表达式
where语句的妙用
$spec = function (Where $where) {
$where->like('username', 'ralph%'); }; $select->where($spec);
$select->order(array('name ASC', 'age DESC'));
$select->limit(5);
$select->offset(10);
Zend\Db\Sql\Where拼凑where语句
equalTo(), lessThan(), greaterThan(), lessThanOrEqualTo(), greaterThanOrEqualTo():
like($identifier, $like):literal($literal, $parameter);isNull($identifier);in($identifier, array $valueSet = array());between($identifier, $minValue, $maxValue);
TabeleGateway 对象意在提供一个能够代表数据表的对象,该对象的方法反映最常见的数据表操作。
class TableGateway extends AbstractTableGateway { public $lastInsertValue; public $table; public $adapter; public function __construct($table, Adapter $adapter, $features = null, ResultSet $resultSetPrototype = null, Sql $sql = null) /** Inherited from AbstractTableGateway */ public function isInitialized(); public function initialize(); public function getTable(); public function getAdapter(); public function getColumns(); public function getFeatureSet(); public function getResultSetPrototype(); public function getSql(); public function select($where = null); public function selectWith(Select $select); public function insert($set); public function insertWith(Insert $insert); public function update($set, $where = null); public function updateWith(Update $update); public function delete($where); public function deleteWith(Delete $delete); public function getLastInsertValue(); }
三.Zend\DI
// 在引导程序中 $di = new Zend\Di\Di(); $di->instanceManager()->setParameters('MyLibrary\DbAdapter', array( 'username' => $config->username, 'password' => $config->password )); // 在每个控制器中 $movieLister = $di->get('MyMovieApp\MovieLister'); foreach ($movieLister as $movie) { // 迭代并显示 $movie }
四.Zend\EventManager
- 实现简单的主题/观察者(subject/observer)模式。
- 实现面向行为的设计。
- 实现事件驱动的架构。
use Zend\EventManager\EventManagerInterface; use Zend\EventManager\EventManager; use Zend\EventManager\EventManagerAwareInterface; class Foo implements EventManagerAwareInterface { protected $events; public function setEventManager(EventManagerInterface $events) { $events->setIdentifiers(array( __CLASS__, get_called_class(), )); $this->events = $events; return $this; } public function getEventManager() { if (null === $this->events) { $this->setEventManager(new EventManager()); } return $this->events; } }
触发事件:$this->getEventManager()->trigger(__FUNCTION__, $this, $params);
监听事件:$foo->getEventManager()->attach('bar', function ($e) use ($log) {
$event = $e->getName(); $target = get_class($e->getTarget()); $params = json_encode($e->getParams()); $log->info(sprintf( '%s called on %s, using params %s', $event, $target, $params )); });
五.Zend\Http
use Zend\Http\Request; $request = Request::fromString(<<<EOS POST /foo HTTP/1.1 \r\n HeaderField1: header-field-value1 HeaderField2: header-field-value2 \r\n\r\n foo=bar& EOS ); // OR, the completely equivalent $request = new Request(); $request->setMethod(Request::METHOD_POST); $request->setUri('/foo'); $request->getHeaders()->addHeaders(array( 'HeaderField1' => 'header-field-value1', 'HeaderField2' => 'header-field-value2', )); $request->getPost()->set('foo', 'bar');
// getPost() 和 getQuery() 都返回,默认情况下,一个 Parameters 对象,该对象继承 ArrayObject $request->getPost()->foo = 'Foo value'; $request->getQuery()->bar = 'Bar value'; $request->getPost('foo'); // 返回 'Foo value' $request->getQuery()->offsetGet('bar'); // 返回 'Bar value'
use Zend\Http\Response; $response = Response::fromString(<<<EOS HTTP/1.0 200 OK HeaderField1: header-field-value HeaderField2: header-field-value2 <html> <body> Hello World </body> </html> EOS); // OR $response = new Response(); $response->setStatusCode(Response::STATUS_CODE_200); $response->getHeaders()->addHeaders(array( 'HeaderField1' => 'header-field-value', 'HeaderField2' => 'header-field-value2', )); $response->setContent(<<<EOS <html> <body> Hello World </body> </html> EOS);
六.Zend\Json
Zend\Json用法包括使用两个可用的public static方法: Zend\Json\Json::encode()和Zend\Json\Json::decode()
// Retrieve a value:
$phpNative = Zend\Json\Json::decode($encodedValue);
// Encode it to return to the client:
$json = Zend\Json\Json::encode($phpNative);
|