The factory pattern is usually used to return different classes similar to interfaces. A common use of factories is to create polymorphic providers.
Usually the factory pattern has a key construct, which is a static method usually named factory. This static method can accept any number of parameters and must return an object.
<spanmicrosoft yahei><span>interface</span><span> IDatabase { //...</span><span>public</span> <span>function</span> query(<span>$sql</span><span>);</span><span> } </span><span>class</span><span> DBFactory { </span><span>public</span> <span>static</span> <span>function</span> create(<span>$type</span><span>){ </span><span>$db</span> = <span>null</span><span>; </span><span>switch</span> (<span>$type</span><span>) { </span><span>case</span> 'mysql': <span>$db</span> = <span>new</span> <span>Mysql</span>(<span>/*</span><span>*arguments</span><span>*/</span><span>); </span><span>break</span><span>; </span><span>case</span> 'sqlite': <span>$db</span> = <span>new</span> Sqlite(<span>/*</span><span>*arguments</span><span>*/</span><span>); </span><span>break</span><span>; </span><span>case</span> 'pgsql': <span>$db</span> = <span>new</span> PGsql(<span>/*</span><span>*arguments</span><span>*/</span><span>); </span><span>break</span><span>; </span><span>default</span>: <span>#</span><span> code...</span> <span>break</span><span>; } </span><span>return</span> <span>$db</span><span>; } } </span><span>class</span> <span>Mysql</span> <span>implements</span><span> IDatabase { </span><span>//... </span><span>public</span> <span>function</span> query(<span>$sql</span><span>){ }</span><span> } </span><span>/*</span><span>*other class ...</span><span>*/</span></spanmicrosoft>
<spanmicrosoft yahei><span>$db</span> = DBFactory::create('mysql'<span>); </span><span>$db</span>->query('show database');</spanmicrosoft>
The above introduces the design pattern in PHP: factory pattern, including the content of PHP factory pattern. I hope it will be helpful to friends who are interested in PHP tutorials.