Home > Article > Backend Development > php设计模式 适配器模式,php设计模式_PHP教程
适配器模式,可以将截然不同的函数接口封装成统一的API;
应用举例,PHP的数据库操作有Mysql、Mysqli、pdo三种,可以用适配器模式统一成一致,类似的场景还有cache适配器,将memcache、redis,file,apc等不同的缓存函数统一成一致。
IDatabase.php
<?<span>php namespace Baobab; </span><span>interface</span><span> IDatabase{ </span><span>function</span> connect(<span>$host</span>, <span>$user</span>, <span>$passwd</span>, <span>$dbname</span><span>); </span><span>function</span> query(<span>$sql</span><span>); </span><span>function</span> fetch_result(<span>$result</span><span>); </span><span>function</span><span> close(); }</span>
Mysqli.php
<?<span>php namespace Baobab\Database; </span><span>use</span><span> Baobab\IDatabase; </span><span>class</span> Mysqli <span>implements</span><span> IDatabase{ </span><span>protected</span> <span>$conn</span><span>; </span><span>function</span> connect(<span>$host</span>, <span>$user</span>, <span>$passwd</span>, <span>$dbname</span><span>){ </span><span>$conn</span> = <span>mysqli_connect</span>(<span>$host</span>, <span>$user</span>, <span>$passwd</span>, <span>$dbname</span><span>); mysqli_set_charset(</span><span>$conn</span>, 'utf8'<span>); </span><span>$this</span>->conn = <span>$conn</span><span>; } </span><span>function</span> query(<span>$sql</span><span>) { </span><span>return</span> <span>mysqli_query</span>(<span>$this</span>->conn, <span>$sql</span><span>); } </span><span>function</span> fetch_result(<span>$result</span><span>){ </span><span>return</span> mysqli_fetch_all(<span>$result</span><span>); } </span><span>function</span><span> close() { </span><span>mysqli_close</span>(<span>$this</span>-><span>conn); } }</span>
Pdo.php
<?<span>php namespace Baobab\Database; </span><span>use</span><span> Baobab\IDatabase; </span><span>class</span> Pdo <span>implements</span><span> IDatabase{ </span><span>protected</span> <span>$conn</span><span>; </span><span>function</span> connect(<span>$host</span>, <span>$user</span>, <span>$passwd</span>, <span>$dbname</span><span>){ </span><span>$conn</span> = <span>new</span> \PDO("mysql:dbname=<span>$dbname</span>;host=<span>$host</span>", <span>$user</span>, <span>$passwd</span><span>); </span><span>$this</span>->conn = <span>$conn</span><span>; } </span><span>function</span> query(<span>$sql</span><span>){ </span><span>return</span> <span>$this</span>->conn->query(<span>$sql</span><span>); } </span><span>function</span> fetch_result(<span>$result</span><span>){ } </span><span>function</span><span> close() { </span><span>unset</span>(<span>$this</span>-><span>conn); } }</span>
index.php
<span>$db</span> = <span>new</span><span> Baobab\Database\Mysqli(); </span><span>$db</span>->connect('127.0.0.1', 'root', '', 'test'<span>); </span><span>$res</span> = <span>$db</span>->query('select * from ha_cl'<span>); </span><span>print_r</span>(<span>$db</span>->fetch_result(<span>$res</span><span>)); </span><span>$db</span>->close();