Skip to content

Commit

Permalink
Make factory instantiable.
Browse files Browse the repository at this point in the history
  • Loading branch information
hschletz committed Jun 2, 2024
1 parent 1d41b37 commit cd5a660
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,24 @@ connection object and the DBMS type it connects to. It then sets up and returns
an object of an appropriate subclass of *Nada\Database\AbstractDatabase*, which
is the main interface for all subsequent operations.

Alternatively, you can instantiate and invoke the factory:

$pdo = new \PDO($dsn, $user, $password);
$factory = new \Nada\Factory();
$database = $factory($pdo);

This is useful if you want to inject the factory as a dependency of another
class:

class MyClass
{
public funcion __construct(\Nada\Factory $factory, \PDO $pdo)
{
$database = $factory($pdo);
...
}
}

No extra database connection is initiated - it is up to the application to
connect to the database as usual. NADA can safely reuse any connection. No
changes to the connection object are made unless explicitly requested.
Expand Down
29 changes: 28 additions & 1 deletion src/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@

namespace Nada;

use Laminas\Db\Adapter\Adapter;
use Nada\Database\AbstractDatabase;
use PDO;

/**
* Factory class to create a NADA interface from a database link
*
Expand All @@ -39,12 +43,35 @@
* $pdo = new \PDO($dsn, $user, $password);
* $database = \Nada\Factory::getDatabase($pdo);
*
* Alternatively, you can instantiate and invoke the factory:
*
* $pdo = new \PDO($dsn, $user, $password);
* $factory = new \Nada\Factory();
* $database = $factory($pdo);
*
* This is useful if you want to inject the factory as a dependency of another
* class:
*
* class MyClass
* {
* public funcion __construct(\Nada\Factory $factory, \PDO $pdo)
* {
* $database = $factory($pdo);
* ...
* }
* }
*
* The result is a \Nada\Database\AbstractDatabase derived object which is aware
* of the database link it was created from and the DBMS type it connects to.
* All further interaction starts with this object.
*/
class Factory
{
public function __invoke(PDO | Adapter $link): AbstractDatabase
{
return static::getDatabase($link);
}

/**
* Factory method to create database interface
*
Expand All @@ -58,7 +85,7 @@ static function getDatabase($link)
// Determine the database abstraction layer
if ($link instanceof \PDO) {
$class = 'Pdo';
} elseif ($link instanceof \Laminas\Db\Adapter\Adapter) {
} elseif ($link instanceof Adapter) {
$class = 'LaminasDb';
} else {
throw new \InvalidArgumentException('Unsupported link type');
Expand Down

0 comments on commit cd5a660

Please sign in to comment.