Object Oriented PHP

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

    #1

    Object Oriented PHP

    Hello again,

    I have written three classes : validate.class. php,
    report_handler. class.php, sentry.class.ph p.

    The problem is that the "validate" class uses the "reporting" class and
    the "sentry" uses the "validate" that uses the "reporting" .

    So I end up having something like that inside sentry.class.ph p:
    $validate->report->getReport();

    But although that's working... it doesn't seem to be really OO :p

    So can you tell me what I can do ?

    If what I am saying doesn't make any sense at all... let me know and I
    will try to explain it better.

    Bellow I have some snippets from each class that may help you to
    understand what I am trying to do.
    *************** *************** *************** *************** ********
    class report_handler {
    ....
    /* This Function populates the array with reports (ERRORS,MESSAGE S)
    * Syntax: setReport($repo rtType,$string)
    */
    function setReport($repo rtType,$string= '') {
    if($this->validateReport Types($reportTy pe)) {
    $this->counter++;
    $this->report[$this->counter] = array( 'category' => $reportType,
    'description' => $string);
    }
    else
    echo "Report type '".$reportType. "' is not valid";
    }
    /* Output the report to the user
    */
    function getReport() {
    if(is_array($th is->report))
    {
    foreach($this->report as $i => $value)
    {
    echo "<pre>".
    $value['category'].': '.
    $value['description']
    ."</pre>";
    }
    }
    }
    ....
    }
    /*************** **END of class report_handler* *************** ****/

    class validate {

    function validate()
    {
    $this->report = new report_handler( );
    }

    function checkEmail($ema il)
    {
    // checks proper syntax
    if(
    !preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/',
    $email))
    {
    $this->report->setReport('Err or','Syntax Error');
    return false;
    }
    ....
    }
    }
    /*************** **END of class validate *************** *****/
    class sentry {
    var $user_id;
    var $session_timeou t;

    function sentry()
    {
    $this->report = new report_handler;
    }
    ....

    function validateLoginFo rm()
    {
    $validate = new validate();
    if($validate->checkEmail($_P OST['email']))
    {
    $this->loginUserNam e = $_POST['email'];
    $this->loginPasswor d = $_POST['passwd'];
    return true;
    }
    else
    {
    $validate->report->getReport();
    return false;
    }
    }
    .....
    }
    /*************** **END of class sentry********* ***********/




    Thanks a lot for reading and for any help you may provide.
    Angelos.
  • ZeldorBlat

    #2
    Re: Object Oriented PHP

    >But although that's working... it doesn't seem to be really OO :p

    Sure it is. OO is just as much aggregation and composition as it is
    inheritance. In fact, inheritance limits you in that you can't change
    the inheritance at runtime (well, in PHP you can, but OO purists would
    have a heart attack). You can modify the composition, however.

    In your case, you could mimic your "uses" idea with inheritance. For
    instance, you could have validate extend reporting and have sentry
    extend validate. But you also need to consider if this makes sense.
    Is sentry really a more specific instance of validate? Is validate
    really a more specific instance of report? I think the answer is no.
    You probably want to use validate with things other than reports.

    Based on your example, I think you could probably make validate() a
    static method and pass it a report object as a parameter. Or better
    yet, create an interface (or abstract class) called "Validatabl e" or
    something. This interface should define all the methods you might need
    to validate something (such as getContent(), getEmail(), or
    setError()). The report class can then implement/extend Validatable.
    Then, inside your validate() method, check that the parameter is an
    instance of Validatable and do what you need to do. This way, you can
    make anything validatable (an email address, form input, etc.) and just
    pass it in.

    Comment

    • Meião

      #3
      Re: Object Oriented PHP

      i wouldn't use the variable report directly.
      $validate->report->getReport();

      i'd make:
      $validate->getReport();

      and in class validate, make a method:
      function getReport(){
      $this->report->getReport();
      }

      seems a little more OO to me
      (well at least, at OO classes i learnt to make variables private)

      Comment

      • David Haynes

        #4
        Re: Object Oriented PHP

        From a pure OO perspective, 'validate' is a method not an object.
        What you really have is an emailAddress object that requires a validate
        method.

        Something like:
        $email = new emailAddress($_ POST['email']);
        if( $email->isValid() {
        ...
        } else {
        ...
        }

        -david-

        Angelos wrote:[color=blue]
        > Hello again,
        >
        > I have written three classes : validate.class. php,
        > report_handler. class.php, sentry.class.ph p.
        >
        > The problem is that the "validate" class uses the "reporting" class and
        > the "sentry" uses the "validate" that uses the "reporting" .
        >
        > So I end up having something like that inside sentry.class.ph p:
        > $validate->report->getReport();
        >
        > But although that's working... it doesn't seem to be really OO :p
        >
        > So can you tell me what I can do ?
        >
        > If what I am saying doesn't make any sense at all... let me know and I
        > will try to explain it better.
        >
        > Bellow I have some snippets from each class that may help you to
        > understand what I am trying to do.
        > *************** *************** *************** *************** ********
        > class report_handler {
        > ...
        > /* This Function populates the array with reports (ERRORS,MESSAGE S)
        > * Syntax: setReport($repo rtType,$string)
        > */
        > function setReport($repo rtType,$string= '') {
        > if($this->validateReport Types($reportTy pe)) {
        > $this->counter++;
        > $this->report[$this->counter] = array( 'category' =>
        > $reportType,
        > 'description' =>
        > $string);
        > }
        > else
        > echo "Report type '".$reportType. "' is not valid";
        > }
        > /* Output the report to the user
        > */
        > function getReport() {
        > if(is_array($th is->report))
        > {
        > foreach($this->report as $i => $value)
        > {
        > echo "<pre>".
        > $value['category'].': '.
        > $value['description']
        > ."</pre>";
        > }
        > }
        > }
        > ...
        > }
        > /*************** **END of class report_handler* *************** ****/
        >
        > class validate {
        >
        > function validate()
        > {
        > $this->report = new report_handler( );
        > }
        >
        > function checkEmail($ema il)
        > {
        > // checks proper syntax
        > if(
        > !preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/',
        > $email))
        > {
        > $this->report->setReport('Err or','Syntax Error');
        > return false;
        > }
        > ....
        > }
        > }
        > /*************** **END of class validate *************** *****/
        > class sentry {
        > var $user_id;
        > var $session_timeou t;
        >
        > function sentry()
        > {
        > $this->report = new report_handler;
        > }
        > ....
        >
        > function validateLoginFo rm()
        > {
        > $validate = new validate();
        > if($validate->checkEmail($_P OST['email']))
        > {
        > $this->loginUserNam e = $_POST['email'];
        > $this->loginPasswor d = $_POST['passwd'];
        > return true;
        > }
        > else
        > {
        > $validate->report->getReport();
        > return false;
        > }
        > }
        > ....
        > }
        > /*************** **END of class sentry********* ***********/
        >
        >
        >
        >
        > Thanks a lot for reading and for any help you may provide.
        > Angelos.[/color]

        Comment

        • Chung Leong

          #5
          Re: Object Oriented PHP

          Angelos wrote:[color=blue]
          > But although that's working... it doesn't seem to be really OO :p
          >
          > So can you tell me what I can do ?[/color]

          Errrr, stop pretending that you have an OOP design? You're basically
          programming procedurally with the use of classes. If your class methods
          are regular regular functions, you wouldn't be having the problem
          you're having now.

          One of the tenets of OOP is encapsulation--codes deal with a different
          concerns should be independent and self-contained. When you have one
          class that does one thing (say validation) directly dependent on
          another class, doing something quite unrelated (say logging), the
          design is rubbish. For the situation you described, you would want some
          kind of slot/socket mechanism. In a typical PHP script though, such
          complexity is really an overkill.

          Comment

          • Angelos

            #6
            Re: Object Oriented PHP

            > Errrr, stop pretending that you have an OOP design?

            I don't pretend to have an OOP design... I know that it is close but not
            OO !
            [color=blue]
            > One of the tenets of OOP is encapsulation--codes deal with a different
            > concerns should be independent and self-contained. When you have one
            > class that does one thing (say validation) directly dependent on
            > another class, doing something quite unrelated (say logging), the
            > design is rubbish.[/color]

            Why do you say that the design is rubbish ? In OO everything can relate
            to anything ... Who says that a logging Class should not relate with a
            Validation Class...
            [color=blue]
            >For the situation you described, you would want some
            > kind of slot/socket mechanism. In a typical PHP script though, such
            > complexity is really an overkill.[/color]

            I don't even know how you went into socket programming...
            /*************** *************** *************** *************** ***********/
            First of all... I am not going to write a complete OO script because
            full OO support in PHP was added in version 5 and my server doesn't
            support Ver 5.

            Second the only reason that I am using Classes and try to apply OO
            concepts in my script is that I want to write reusable code.

            I want to have modular program that its module is independent and can be
            installed or uninstalled in any time.

            I used to program in JAVA and I was really used to Analysis Design and
            Implementation process but the last year I started learning PHP and got
            lazy...

            Anyway thanks for the replies, the "extend" of a class is a solution but
            not the best ... I am going to start re-designing something that makes
            more sense ...

            Comment

            • Chung Leong

              #7
              Re: Object Oriented PHP

              Angelos wrote:[color=blue]
              > Why do you say that the design is rubbish ? In OO everything can relate
              > to anything ... Who says that a logging Class should not relate with a
              > Validation Class...[/color]

              The basic premise of OO is that objects in a program behave as objects
              in the real world. A class should only be dependent on classes that are
              its constituent parts. A log meant to be used across an application
              obviously isn't be a part of the data validator.

              In what I consider a proper OO design, the validator class would expose
              a connection point that is then plugged into a slot in the logging
              class. The two classes remain independent of each other. One broadcasts
              signals to any possible listeners, while the other handle signals
              emitted by any possible sources. If suddenly I don't want logging, all
              I have to do is break the connection. If I want to add another
              notification mechanism, I just grab another connection point and stick
              it somewhere else. Neither case involves a change to the class.

              Of course, a full-on OO treatment is overkill for most PHP apps. Going
              through multiple layers of abstractions to echo a line of text is vain.
              A half-hearted attempt at OO, I would say though, is pointless and
              counterproducti ve. You have functions defined somewhere that you want
              to call--that's procedure oriented programming. Wrapping them in a
              class doesn't change anything--the basic approach is still the
              same--except now you have a object to worry about.

              Comment

              Working...