Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Sep 2012
    Thanked 0 Times in 0 Posts

    Am I using the factory pattern correctly?

    Hello, I am currently investigating the factory pattern and think I understand it, but just want to make sure I am doing it right with my connection example below for different ways of connecting to a database.

    1 - First of all I have set the type of connection I want in this case a PDO one

    PHP Code:
    $connection dbConnectionFactory::getConnection('pdo'); 
    2- Use a factory to use the approprate connection

    PHP Code:
    class dbConnectionFactory {
    public function 
    getConnection($type) {
    $type) {
    'pdo': Return PDOConnection::myConn(); break;
    'mysql': Return MYSQLConnection::myConn(); break;
    'mysqli': Return MYSQLiConnection::myConn(); break;

    3 - Then grab the PDOConnection from the factory. This then loads myConn() which is a basic singleton pattern, which returns one single instance

    So my question is in the above am I using it right for a factory pattern or have I misunderstood? Any improvements on this and the way I connect that anyone can advise/suggest?

    Thank you

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Saskatoon, Saskatchewan
    Thanked 2,662 Times in 2,631 Posts
    The only thing that's wrong is that getConnection needs to be static. Without it, it will be triggering an E_STRICT error on access, but I *believe* it will still function properly. Same goes for the singleton's as well; make sure the myconn is static and returning a static instance stored either local to the class, or local to the static method (I wouldn't do the latter unless you are using a trait instead).


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts