1. Go to this page and download the library: Download kael-shipman/factory library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kael-shipman / factory example snippets
>
> // FactoryInterface.php
> namespace YourNamespace;
>
> interface FactoryInterface {
> public function newMyObject();
> public function newYourObject();
> }
>
// Get your factory instance
$f = MyFactory::getInstance();
// Use it to create a new app instance
$app = $f->new('app');
// Since you can't guarantee *what* app instance it gave you, you have to verify that it implements the interface you're expecting
if (!($app instanceof AppIWannaRun)) throw new RuntimeException("App returned by factory must be of type `AppIWannaRun`");
// Now run it
$app->run();
class MyApp {
protected $factory;
protected $db;
// Here, you have to pass an instance of your factory to the app on construct, along with an instance of a DB
public function __construct(FactoryInterface $f, DatabaseInterface $db) {
$this->factory = $f;
$this->db = $db;
}
// Do lots of stuff here ......
// Now here's an internal method
protected function getInternalThings() {
// Get things from the DB
$things = $this->db->query('SELECT * FROM `things`');
// Create a thing collection
$thingCollection = $this->factory->new('collection', 'things');
// Iterate over the db results, adding things to the collection
foreach($things as $thing) {
$thingCollection[] = $this->factory->create('thing', null, $thing);
}
// Return the collection
return $thingCollection;
}
// ...
}
namespace MyNamespace;
class MyFactory extends \KS\Factory {
// Signature has to match the original Factory::getClass method
public function getClass(string $type, string $subtype=null) {
// Return the class as a string including namespace
if ($type == 'app') {
// Always a good practice to check for subtype, even if you don't need one today
if (!$subtype || $subtype == 'generic') return '\\MyNamespace\\App';
}
if ($type == 'collection') {
if ($subtype == 'thing') return '\\MyNamespace\\ThingsCollection';
// Notice, if we're asking for a subtype we don't know how to create, it falls through
}
if ($type == 'thing') {
if (!$subtype || $subtype == 'generic') return '\\MyNamespace\\Thing';
}
// Fall through to parent
return parent::getClass($type, $subtype);
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.