OOP database tables <-> php interface (semi LONG)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • amygdala

    #16
    Re: OOP database tables &lt;-&gt; php interface (semi LONG)


    "Toby A Inkster" <usenet200703@t obyinkster.co.u kschreef in bericht
    news:r1s3f4-4kp.ln1@ophelia .g5n.co.uk...
    amygdala wrote:
    >
    >Could you by any chance provide the simplest example of an occassion
    >where making the constructor private makes sense? Cause I can't think of
    >a valuable situation right now.
    >
    OK -- how about this -- you have a Database class, but you want to make
    sure that your scripts only ever open a single connection to the database.
    You don't want both, say, a User object and an Article object to open
    their own individual connections like this:
    >
    <?php
    class User
    {
    private $db;
    public function __construct ()
    {
    $this->db = new Database(/*...*/);
    }
    }
    class Article
    {
    private $db;
    public function __construct ()
    {
    $this->db = new Database(/*...*/);
    }
    }
    ?>
    >
    And so to prevent this, you make the Database's constructor function
    private. This is known as the "singleton" design pattern in the PHP
    manual. (It's on the same page as the factory design pattern!)
    >
    <?php
    class Database
    {
    public function query ($q) { /*...*/ }
    public function type () { /*...*/ }
    public function escape_string ($s) { /*...*/ }
    private function __construct ($dsn, $username, $password) { /*...*/ }
    >
    private static $instance;
    public static singleton ($dsn, $username, $password)
    {
    if (!isset(self::$ instance))
    self::$instance = new Database ($dsn, $username, $password);
    >
    return self::$instance ;
    }
    }
    ?>
    >
    So now you must use "Database::sing leton()" instead of "new Database" to
    get a database object, but the singleton class method will always return a
    pointer to the same Database object -- it won't create a brand new one!
    >
    And your code becomes:
    >
    <?php
    class User
    {
    private $db;
    public function __construct ()
    {
    $this->db = Database::singl eton(/*...*/);
    }
    }
    class Article
    {
    private $db;
    public function __construct ()
    {
    $this->db = Database::singl eton(/*...*/);
    }
    }
    ?>
    >
    Aaah yes of course, I read about such an example at one point in time. And
    at first I didn't understand how such an object could ever be made since the
    constructor is private. So I left it for what it was. But the object is of
    course constructed from within the object itself with its singleton method.
    Doh! ;-)
    It all makes sense now. Thanks Toby.



    Comment

    • amygdala

      #17
      Re: OOP database tables &lt;-&gt; php interface (semi LONG)


      "Jerry Stuckle" <jstucklex@attg lobal.netschree f in bericht
      news:mpmdnf_eob am7ILbnZ2dnUVZ_ riknZ2d@comcast .com...
      amygdala wrote:
      <snip>
      And as you add more types and subtypes, this gets longer and longer. And
      slower and slower. And harder to maintain and more subject to errors.
      <snip>
      And you'll have to add more custom validators plus hooks for them.
      <snip>
      And what about cases where you need non-consecutive numbers? Such as
      those from the set (1, 2, 3, 5, 8, 13, 21...)? Another custom
      validator...
      <snip>
      The generic will be much larger, much slower and much harder to maintain.
      <snip>
      Yes, it's easy to get one idea in your mind as the best way and stick to
      it too long. You need to be flexible. Even after 40 years of programming
      I sometimes have to change my approach because someone shows me a better
      way.
      <snip>
      I create db objects all the time. But they have get and set functions for
      each field (at least the appropriate ones). They are quite handy for a
      number of purposes - the biggest one being abstracting the database
      access. But then that's their major purpose.
      >
      For instance - one I'm on right now. I have a site coded in VBScript
      using Access. I want to change it to PHP and MySQL. However, for various
      reasons this needs to be done in stages. The Access database has over 30
      tables, ranging from 2 columns to over 40 columns per table.
      >
      We're (others are involved - it's a big site) creating DB objects to
      interface the Access tables. These will handle the actual SQL calls and
      isolates the program from the database being used (or even flat files, if
      necessary).
      >
      Next we'll creating business objects - these objects translate between the
      program and the database objects, and convert what's in the tables to a
      format the rest of the program needs. This isolates the rest of the code
      from the database table design (i.e. if we need to change one or more
      tables, this and the db objects are all that will need changing).
      >
      We'll then convert sections of the site at a time. Once we get a section
      converted, we'll bring it online.
      >
      When we're done and can change from the Access database to MySQL, we'll
      change the Database layer and move the data. If at the same time we need
      to change some of the table design, this will be handled between the
      database and business object layers. But any changes will be isolated to
      those layers.
      >
      Note the business object layer isn't always needed. But due to the
      complexity of the site and how many tables are interrelated, we decided it
      would be better to use them here.
      >
      These are the benefits of database objects (and OO in general).
      But I would hate to use your fieldspec idea in this case. It would make
      things much harder to troubleshoot, and we'd end up with a lot of
      specialized validators. The result would rapidly become unmanageable.
      >
      So we're putting in the set and get functions for several hundred table
      columns. Additionally, we're doing a similar number on the business
      object end. And depending on the data, it may be validated in either
      level.
      >
      Some darned good points Jerry. Especially the getting too large and slow
      parts are starting to convince me

      Good point about the flexibility too! I try my best to keep up a flexible
      attitude. The thing is though that I often get caught up in trying to
      generalize things too much and/or mixing up in what 'layer' certain routines
      should take place.

      For instance, as you put in your example: Where would validating in the
      bussiness objects stop and validating in DB objects start, or vice versa.
      Are there some ground rules or methodologies for determining this in early
      stages of coding a project? Do you know of some pointers; some good clear
      articles perhaps?

      Just out of curiousity though. I assume that you _do_ have some sort of
      generic validator routines for repeating column / field validation right?
      For instance a generic validateEmail() function which you call for the
      specific task when doing a setEmail. You're not reinventing the wheel in
      each and every getter methods right?

      Thanks again!


      Comment

      • Jerry Stuckle

        #18
        Re: OOP database tables &lt;-&gt; php interface (semi LONG)

        amygdala wrote:
        "Jerry Stuckle" <jstucklex@attg lobal.netschree f in bericht
        news:mpmdnf_eob am7ILbnZ2dnUVZ_ riknZ2d@comcast .com...
        >amygdala wrote:
        >
        <snip>
        >
        >And as you add more types and subtypes, this gets longer and longer. And
        >slower and slower. And harder to maintain and more subject to errors.
        >
        <snip>
        >
        >And you'll have to add more custom validators plus hooks for them.
        >
        <snip>
        >
        >And what about cases where you need non-consecutive numbers? Such as
        >those from the set (1, 2, 3, 5, 8, 13, 21...)? Another custom
        >validator...
        >
        <snip>
        >
        >The generic will be much larger, much slower and much harder to maintain.
        >
        <snip>
        >
        >Yes, it's easy to get one idea in your mind as the best way and stick to
        >it too long. You need to be flexible. Even after 40 years of programming
        >I sometimes have to change my approach because someone shows me a better
        >way.
        >
        <snip>
        >
        >I create db objects all the time. But they have get and set functions for
        >each field (at least the appropriate ones). They are quite handy for a
        >number of purposes - the biggest one being abstracting the database
        >access. But then that's their major purpose.
        >>
        >For instance - one I'm on right now. I have a site coded in VBScript
        >using Access. I want to change it to PHP and MySQL. However, for various
        >reasons this needs to be done in stages. The Access database has over 30
        >tables, ranging from 2 columns to over 40 columns per table.
        >>
        >We're (others are involved - it's a big site) creating DB objects to
        >interface the Access tables. These will handle the actual SQL calls and
        >isolates the program from the database being used (or even flat files, if
        >necessary).
        >>
        >Next we'll creating business objects - these objects translate between the
        >program and the database objects, and convert what's in the tables to a
        >format the rest of the program needs. This isolates the rest of the code
        >from the database table design (i.e. if we need to change one or more
        >tables, this and the db objects are all that will need changing).
        >>
        >We'll then convert sections of the site at a time. Once we get a section
        >converted, we'll bring it online.
        >>
        >When we're done and can change from the Access database to MySQL, we'll
        >change the Database layer and move the data. If at the same time we need
        >to change some of the table design, this will be handled between the
        >database and business object layers. But any changes will be isolated to
        >those layers.
        >>
        >Note the business object layer isn't always needed. But due to the
        >complexity of the site and how many tables are interrelated, we decided it
        >would be better to use them here.
        >>
        >These are the benefits of database objects (and OO in general).
        >But I would hate to use your fieldspec idea in this case. It would make
        >things much harder to troubleshoot, and we'd end up with a lot of
        >specialized validators. The result would rapidly become unmanageable.
        >>
        >So we're putting in the set and get functions for several hundred table
        >columns. Additionally, we're doing a similar number on the business
        >object end. And depending on the data, it may be validated in either
        >level.
        >>
        >
        Some darned good points Jerry. Especially the getting too large and slow
        parts are starting to convince me
        >
        Good point about the flexibility too! I try my best to keep up a flexible
        attitude. The thing is though that I often get caught up in trying to
        generalize things too much and/or mixing up in what 'layer' certain routines
        should take place.
        >
        For instance, as you put in your example: Where would validating in the
        bussiness objects stop and validating in DB objects start, or vice versa.
        Are there some ground rules or methodologies for determining this in early
        stages of coding a project? Do you know of some pointers; some good clear
        articles perhaps?
        >
        Generally the business object is at least (if not more) restrictive than
        the database object, so the validation would be done in the business
        object. I don't normally validate in the database object if it's not
        being accessed by the program itself.
        Just out of curiousity though. I assume that you _do_ have some sort of
        generic validator routines for repeating column / field validation right?
        For instance a generic validateEmail() function which you call for the
        specific task when doing a setEmail. You're not reinventing the wheel in
        each and every getter methods right?
        >
        Thanks again!
        >
        >
        Not necessarily functions - just some spare code running around. I
        either copy and paste into a function or create a validator function
        with it, depending on my needs.

        I generally don't create a separate function just to validate one
        attribute. I just put the code directly in the setxxx function.

        --
        =============== ===
        Remove the "x" from my email address
        Jerry Stuckle
        JDS Computer Training Corp.
        jstucklex@attgl obal.net
        =============== ===

        Comment

        • amygdala

          #19
          Re: OOP database tables &lt;-&gt; php interface (semi LONG)


          "Toby A Inkster" <usenet200703@t obyinkster.co.u kschreef in bericht
          news:rrr2f4-4kp.ln1@ophelia .g5n.co.uk...
          amygdala wrote:
          >
          >I'm a little confused about the 'factory design pattern' though. Let me
          >see
          >if I understand this correctly. Does the factory design pattern in this
          >case
          >refer to the fact that you have different interfaces in one Class (in
          >this
          >case class User) to create the object, depending on the purpose it
          >serves.
          >
          Yep, precisely. You create a static method to produce an object which
          would normally go further than the plain constructor function in terms of
          setting object properties.
          >
          On some occasions you may even want to make the main constructor method
          for the class private instead of public to force all objects to be created
          via the factory.
          I think I am starting to get the hang of this factory design pattern. My
          class User up until now looks something like (stripped version, and needs
          custom error handling, etc.):

          <?php

          require_once( 'Database.class .php' );

          class User
          {
          // database handler values
          private static $dbh;
          private static $dbt = DB_TABLE_USER;

          // table columns
          private $id;
          private $userType;
          private $username;
          private $password;
          private $email;
          private $active;
          private $timeCreated;
          private $timeActivated;
          private $timeUpdated;

          public function __construct()
          {
          self::$dbh = Database::getIn stance( DB_INTERFACE, DB_HOST, DB_SCHEMA,
          DB_USERNAME, DB_PASSWORD );
          }

          public function getUsername()
          {
          return $this->username;
          }

          // and a bunch of other getter and setter methods

          public static function getUserById( $id )
          {
          if( is_mysql_int( $id, true ) )
          {
          self::$dbh = Database::getIn stance( DB_INTERFACE, DB_HOST, DB_SCHEMA,
          DB_USERNAME, DB_PASSWORD );
          $sql = 'SELECT * FROM ' . self::$dbt . ' WHERE id = :id LIMIT 1';
          $sth = self::$dbh->prepare( $sql );
          try
          {
          $sth->execute( array(
          ':id' =$id
          )
          );
          }
          catch( PDOException $e )
          {
          die( $e->getMessage() . ' on line: ' . __LINE__ );
          }
          $row = $sth->fetch( PDO::FETCH_ASSO C );
          if( $row )
          {
          $user = new User();
          foreach( $row as $column =$value )
          {
          $user->{ $column } = $value;
          }
          return $user;
          }
          echo 'no user found!';
          return NULL;
          }
          echo 'invalid id!';
          return NULL;
          }
          }
          ?>

          A few questions though:

          Since I would like to have only one database handler that can be accessed by
          both the constructor and the factory method (?) getUserById() I decided to
          declare $dbh static. Does this make sense? If so, it seems I'm not allowed
          to declare it all in one go at the start of the class like so:

          private static $dbh = Database::getIn stance( DB_INTERFACE, DB_HOST,
          DB_SCHEMA, DB_USERNAME, DB_PASSWORD );

          Any ideas why not?

          But what is of more concern for me right now is the following:

          A user should be able to register and later on login to the website I'm
          building. Logging in, seems pretty obvious, should be a method of the User
          class, which returns a User object just like getUserById(). But would a
          register method be a logical thing to put in the User class? Or would you
          put that somewhere else?

          Thank you once more for any insight.


          Comment

          • Toby A Inkster

            #20
            Re: OOP database tables &lt;-&gt; php interface (semi LONG)

            amygdala wrote:
            Since I would like to have only one database handler that can be accessed by
            both the constructor and the factory method (?) getUserById() I decided to
            declare $dbh static. Does this make sense?
            It makes sense, but a better solution would be to make your database
            object into a singleton class. That is, similar to the Database object
            here:

            http://message-id.net/<r1s3f4-4kp.ln1@ophelia .g5n.co.uk>

            --
            Toby A Inkster BSc (Hons) ARCS
            Contact Me ~ http://tobyinkster.co.uk/contact
            Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux

            * = I'm getting there!

            Comment

            • amygdala

              #21
              Re: OOP database tables &lt;-&gt; php interface (semi LONG)


              "Toby A Inkster" <usenet200703@t obyinkster.co.u kschreef in bericht
              news:dclbf4-4kp.ln1@ophelia .g5n.co.uk...
              amygdala wrote:
              >
              >Since I would like to have only one database handler that can be accessed
              >by
              >both the constructor and the factory method (?) getUserById() I decided
              >to
              >declare $dbh static. Does this make sense?
              >
              It makes sense, but a better solution would be to make your database
              object into a singleton class. That is, similar to the Database object
              here:
              >
              http://message-id.net/<r1s3f4-4kp.ln1@ophelia .g5n.co.uk>
              >
              Well, that is the case already. Perhaps it was a bit confusion because I
              named the method in the Database object getInstance. I've changed it to
              getSingleton now. (See below).

              But that still doesn't allow me to create the $dbh only once at the
              beginning of the User class like so:

              class User
              {
              private $dbh = Database::getSi ngleton( /* */ );

              private function __construct() {}

              public static function getUserById()
              {
              // use self::$dbh here
              }

              public function saveUser()
              {
              // use self::$dbh here
              }
              }

              Mind you, it's not a big issue, merely a cosmetic one. What I am still
              struggeling more with is the registrate function. Would you consider that a
              User class method. Or should it be in some other object. Or perhaps just be
              a regular function in the global script?


              // class Database code:

              class Database
              {
              protected static $dbh;

              private function __construct() {}

              public static function getSingleton( $interface, $host, $schema, $username,
              $password )
              {
              if ( !isset( self::$dbh ) )
              {
              self::$dbh = new PDO( ( $interface . ':host=' . $host . ';dbname=' .
              $schema ), $username, $password );
              self::$dbh->setAttribute ( PDO::ATTR_ERRMO DE, PDO::ERRMODE_EX CEPTION );
              //self::$dbh->setAttribute ( PDO::MYSQL_ATTR _USE_BUFFERED_Q UERY, TRUE );
              }
              return self::$dbh;
              }

              public function __destruct()
              {
              if ( isset( self::$dbh ) )
              {
              self::$dbh = NULL;
              }
              }
              }


              Comment

              • Toby A Inkster

                #22
                Re: OOP database tables &lt;-&gt; php interface (semi LONG)

                amygdala wrote:
                Mind you, it's not a big issue, merely a cosmetic one. What I am still
                struggeling more with is the registrate function. Would you consider that a
                User class method. Or should it be in some other object. Or perhaps just be
                a regular function in the global script?
                It could be implemented as a regular function, but I'd tend to put it as a
                static factory function in the User class. (i.e. it returns the newly
                registered User as an object -- much like the static login function
                would.) This has the benefit of having internal consistency with the login
                function. (A developer familiar with the login function would have little
                trouble picking up the registration function.) Also, it keeps the function
                "wrapped up" in the User class, so that everything is kept in one place.

                --
                Toby A Inkster BSc (Hons) ARCS
                Contact Me ~ http://tobyinkster.co.uk/contact
                Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux

                * = I'm getting there!

                Comment

                • amygdala

                  #23
                  Re: OOP database tables &lt;-&gt; php interface (semi LONG)


                  "Toby A Inkster" <usenet200703@t obyinkster.co.u kschreef in bericht
                  news:goocf4-4kp.ln1@ophelia .g5n.co.uk...
                  amygdala wrote:
                  >
                  >Mind you, it's not a big issue, merely a cosmetic one. What I am still
                  >struggeling more with is the registrate function. Would you consider that
                  >a
                  >User class method. Or should it be in some other object. Or perhaps just
                  >be
                  >a regular function in the global script?
                  >
                  It could be implemented as a regular function, but I'd tend to put it as a
                  static factory function in the User class. (i.e. it returns the newly
                  registered User as an object -- much like the static login function
                  would.) This has the benefit of having internal consistency with the login
                  function. (A developer familiar with the login function would have little
                  trouble picking up the registration function.) Also, it keeps the function
                  "wrapped up" in the User class, so that everything is kept in one place.
                  Alright Toby, that is reassuring. Thanks for the input.


                  Comment

                  Working...