Hello and welcome to our community! Is this your first visit?
Register
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
    Posts
    76
    Thanks
    61
    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) {
      switch(
    $type) {
          case 
    'pdo': Return PDOConnection::myConn(); break;
          case 
    'mysql': Return MYSQLConnection::myConn(); break;
          case 
    '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
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 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
    •