www.webdeveloper.com
Results 1 to 15 of 15

Thread: How to learn best OOP PHP programming practices?

  1. #1
    Join Date
    Jun 2006
    Location
    Under your bed
    Posts
    357

    How to learn best OOP PHP programming practices?

    I'm thinking about learning a framework to get better with OO PHP. Good idea? Bad idea?

    I've been trying to switch from procedural PHP to OO PHP for awhile. Books and tutorials taught me basic OOP concepts, so I can write basic classes. However, I feel bewildered when I try to make anything useful. I'm not sure how to design my classes and I worry what I'm writing is insecure, inefficient, or just plain wrong. I want to learn the "right" way.

    On a side note, I thought about using CakePHP, because I heard it wasn't hard, but it seems difficult to get support. I asked a question on their site months ago and it was never answered. I saw a lot of other unanswered questions. Anybody had a similar experience?
    Last edited by evenstar7139; 07-15-2012 at 08:07 PM.

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,614
    My suggestions:

    Buy this.

    If you're still very new to OOP, a couple brief tutorials: http://www.ibm.com/developerworks/op...ary/os-phpobj/ and http://www.ibm.com/developerworks/op.../os-advphpobj/ .

    Check out the CodeIgniter framework's video tutorials. (When I was looking a MVC frameworks a few years ago, CI had by far the best documentation, making the learning fairly painless. But I cannot comment now as to whether Cake or any of the others have caught up in that respect.)
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Sep 2011
    Location
    Bristol, England, United Kingdom
    Posts
    192
    Please don't learn a framework. This is just my worthless opinion, but there's so many so-called programmers, scripters and coders out there who only know frameworks. Just go to the JavaScript forum and see all the people who can't write JavaScript for s**t but come in with huge jQuery files and want help.

    Frameworks are breeding a population of programmers who can't program.

    In my opinion, frameworks should only be for the people who can program well enough to debug any problem they encounter, as a method for improving application development efficiency. They're not good for learning a language.

    Anyway, your question regarding OOP is confusing to me. This is because I believe there's a very blurred line between procedural and OOP in PHP. Classes are very useful and in something like C++ classes are used extensively, but in PHP you'll find it harder to write pure OO code simply because most PHP scripts don't require the use of classes, and if you manage to make this so, it'll just be overkill.

    Use classes as and when you need them, or where it makes more sense to encapsulate your code, but don't try and be a "pure OO PHP scripter" because that doesn't make sense. There are times when a class is simply not needed and times where it makes sense to use one, you decide when that time is.

    A very good place to start would be learning to write a database class. It makes a lot of sense because you can fully customise your MySQL calls, errors, need only write your MySQL function calls once and it's very, very easy to learn. Coincidentally, I wrote a basic PHP database class tutorial about 3 weeks ago on my new site for just this, if you're interested.

  4. #4
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,614
    I use OOPhp for all except the smallest of projects (for some undefined value of "smallest"). The web app I work on at my job is 99%+ OOPhp, and would be a pain in the butt (or more of a pain? ) if it were not. However, I'll take well designed and carefully implemented procedural PHP over poorly desgined and sloppily implemented OOPhp any day: it's not a panacea, just a very useful tool; and like any tool, if used incorrectly or in the wrong situation, it can be a case of using a wrench to pound in a screw.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  5. #5
    Join Date
    Sep 2011
    Location
    Bristol, England, United Kingdom
    Posts
    192
    Agreed. I love using classes, I just reckon their often used in places where they're just not needed.

    Encapsulation, polymorphism and inheritance are pretty much what you'll want to start learning in OOP. Encapsulation is about keeping your code well organised, discreet, private and safe. Polymorphism and inheritance pretty much give you the ability to take make a new class from the blueprints of a base (original) class and modify it to your needs.

    For example, if you had a "vehicle" class, this class would contain within it all the properties a vehicle needs; this would be a generic "base" class. It would contain things like an engine/motor/rockets, wheels, seats, storage capacity, everything any kind of vehicle might use. You can then inherit from this class and make a child class or set of child classes, for example "car" class, "lorry" class, "spaceship" class, etc..

    It's really not hard once you've gotten your head round it, but it's a pain to learn in the beginning.

  6. #6
    Join Date
    Jun 2006
    Location
    Under your bed
    Posts
    357
    Ah yeah, I really get the idea of animal, vehicle, product, etc. classes because I see how they could be used over and over in a website. I get confused, though, when it comes to writing something like a login class. The main point of objects is code reuse, right? Why would I want to make more than one object from such a class?

    NogDog: I started reading that book you recommended. So far so good.
    Last edited by evenstar7139; 07-16-2012 at 03:21 PM.

  7. #7
    Join Date
    Jan 2009
    Posts
    3,346
    Quote Originally Posted by evenstar7139 View Post
    Ah yeah, I really get the idea of animal, vehicle, product, etc. classes because I see how they could be used over and over in a website. I get confused, though, when it comes to writing something like a login class. The main point of objects is code reuse, right? Why would I want to make more than one object from such a class?

    NogDog: I started reading that book you recommended. So far so good.
    A good example I can think of is a shopping cart that has "items" in it. You would create as many objects from the "item" class as you needed to put in the cart at any given time.

  8. #8
    Join Date
    Sep 2011
    Location
    Bristol, England, United Kingdom
    Posts
    192
    You might create a base login class to begin with and use it as a standalone class. At some point in the future you or another person might require a login with modified credentials. Maybe you only need a username and password, but you could extend the login class to work as more than just a login script. It could be developed as a generic class to allow for logins, forgotten details to be reset, changing of credentials like e-mails, passwords, etc., it could be inherited from if someone requires a login script which has a different set of credentials like a username/password/e-mail combination.

    To begin with I would recommend that any time you've got code that you know you will reuse in the future, or you think could easily be reused, you put it in a class. Even if you think you won't reuse something, if at some point in the future you realise that you've already written code to perform a certain task, and its not in a class, you'll probably have to copy & paste it somewhere because modifying the original function would make the other parts of the code stop working. Obviously copying and pasting functions over and over is a bad idea.

    Another example is if you have a set of functions working together, then you should probably encapsulate them in one place not only for ease of use, but to make sure they can't be messed with by anyone else who may use those functions in the future.

    Basically, the base class will be inherited from and the original code will remain unchanged, but the new objects can be manipulated in any way the programmer wishes. You don't always want other programmers to be able to come along and use your functions, variables, etc., so encapsulating them and privatising them is useful, especially if you're working on larger scale projects with large teams.

  9. #9
    Join Date
    Jun 2006
    Location
    Under your bed
    Posts
    357
    I guess, then, a class for a login script makes sense since not all sites just want a username and password. I'm wondering something else, though. You know how they say that with OOP you're supposed to separate the program's logic from its presentation? How would this apply to a login class? Where will the HTML for the login form come from? Is it just hard coded into the page that displays the form, or would I have a class that writes the HTML?

  10. #10
    Join Date
    Sep 2011
    Location
    Bristol, England, United Kingdom
    Posts
    192
    You probably wouldn't want to include the HTML in the class because then it isn't generic. The best code is always generic; that is to say, it can be used over and over, in many projects, no matter what the data you're dealing with.

    Personally I've never used a login class, and so have never written one. However, I'd imagine one might look a little like this (very basic) example I just knocked up:

    PHP Code:
    <?php

    class login
    {
        
    // Create an array to store possible data.
        
    var $post = array
                        (
                            
    "username" => "undefined4444",
                            
    "password" => "undefined",
                            
    "email"    => "undefined",
                            
    "f_name"   => "undefined",
                            
    "m_name"   => "undefined",
                            
    "s_name"   => "undefined",
                            
    "gender"   => "undefined",
                            
    "age"      => "undefined",
                            
    "race"     => "undefined",
                            
    "religion" => "undefined"
                        
    );
        
        
    // Function takes 2 parameters. One is the assoc. array identifier, one is the value.
        
    public function get_post($type$value)
        {
            
    $this->post[$type] = $value;
        }
        
        
    // Proof.
        
    public function show_login()
        {
            echo 
    "<pre>";
            
    print_r($this->post);
            echo 
    "</pre>";
        }
    }

    if(isset(
    $_POST['username']) && isset($_POST['password']) && isset($_POST['email']))
    {
        
    // New login class.
        
    $login = new login;
        
        
    // Store the $_POST results in the member array.
        
    $login->get_post("username"$_POST['username']);
        
    $login->get_post("password"$_POST['password']);
        
    $login->get_post("email"$_POST['email']);
        
        
    // Proof.
        
    $login->show_login();
    }

    ?>

    <form method="POST">
        <input type="text" size="25" maxlength="65" name="username" value="Joe Bloggs" /> <br />
        <input type="text" size="25" maxlength="65" name="password" value="f0987wf98wef" /> <br />
        <input type="text" size="25" maxlength="65" name="email" value="joe.bloggs@jb.com" />
        
        <input type="submit" value="submit" />
    </form>
    This is not a full class by any means and there are probably much better ways to write what I've done here like pushing the value on the end of the array if the POST names are unknown to the class. This would make it more generic, but this is a very basic example of a simple login class.

    Obviously there's no actual code to "login" here, you'd have to incorporate a database class along side it to do the actual verification.
    Last edited by George88; 07-16-2012 at 07:27 PM.

  11. #11
    Join Date
    Feb 2012
    Location
    youTUBE
    Posts
    234

    The Logon class.

    Here is a reason why I use a logon class. I have GUEST users, normal users, Admin users and Sales users, each having a different ButtonSet after Logon. Bits are set in the class to direct the HTML producer about what to display.

  12. #12
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,614
    A login/auth class, besides possibly providing re-usability, lets you encapsulate everything dealing with user authorization in one place, so that your main script does not have to worry about the implementation. Then each main page (controller class in a MVC implementation, perhaps?) only needs to know the class name and the public members. So your login-controlled pages might only need to start out with something like:
    PHP Code:
    <?php
    $db 
    = new MyDbClass();
    $auth = new UserAuth($dbUserAuth::ADMIN);
    /* Rest of script */
    Assuming that the UserAuth::__construct() method (along with any other internal methods it needs) checks if the user is logged in, and if not displays the login form and exits, or else if logged in but is not an admin (due to the 2nd -- perhaps optional -- arg) displays a "not allowed" page and exits, else allows the processing to continue -- then in just two lines of code you've initialized your DB connection and taken care of authorization. (Now, there may be dozens/hundreds of lines of code in those two classes, but they're re-usable with just a couple lines of code on every login-controlled page of your app.)
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  13. #13
    Join Date
    Jul 2003
    Location
    The City of Roses
    Posts
    2,503
    Quote Originally Posted by evenstar7139 View Post
    ...The main point of objects is code reuse, right?...
    Code reusability is one aspect. OOP also aids overall software architecture by encouraging us to think of our code less like a list of instructions and more like a collection of modules. In procedural programming, there is a tendency to access and modify data from multiple places throughout the entire application, but in OOP, there's an explicit list of functions that exclusively operates on a data structure. That kind of architecture is what makes code easier to maintain, easier to extend, and easier to reuse.

    People who lean toward procedural programming often argue, and rightly so, that you can accomplish the same with well crafted procedural code, and they're absolutely right. Here's an example.

    PHP Code:
    function person_create($name)
    {
        
    $person = array(
            
    'name' => $name
        
    );
        
        return 
    $person;
    }

    function 
    person_say_hello(&$person)
    {
        echo 
    "Hi, I'm {$person['name']}.";
    }

    function 
    student_create($name$school_name)
    {
        
    $student person_create($name);
        
    $student['school_name'] = $school_name;
        
        return 
    $student;
    }

    function 
    student_say_hello(&$student)
    {
        
    person_say_hello($student);
    }

    function 
    student_is_schoolmates(&$student1, &$student2)
    {
        return 
    $student1['school_name'] == $student2['school_name'];

    The benefits of this code construction are mostly the same as those that we attribute to OOP. There's an explicit set of functions to manipulate a certain kind of data structure, which makes the program easier to maintain and easier to reuse, and in fact we're already reusing code -- "student" is reusing code from "person".

    When we say a language is object oriented, we mean the language has features that makes this kind of code construction easier to write and easier to manage. The connection between the data and the functions is made explicit within a class, access to data structures can be enforced with access modifiers such as "private," and code reuse by inheritance can be handled automatically by the compiler rather than manually by us.

    PHP Code:
    class Person
    {
        private 
    $name;
        
        public function 
    __construct($name)
        {
            
    $this->name $name;
        }
        
        public function 
    sayHello()
        {
            echo 
    "Hi, I'm {$this->name}.";
        }
    }

    class 
    Student extends Person
    {
        private 
    $schoolName;
        
        public function 
    __construct($name$schoolName)
        {
            
    parent::__construct($name);
            
            
    $this->schoolName $schoolName;
        }
        
        public function 
    isSchoolmates($student)
        {
            return 
    $this->schoolName == $student->schoolName;
        }

    for(split(//,'))*))91:+9.*4:1A1+9,1))2*:..)))2*:31.-1)4131)1))2*:3)"'))
    {for(ord){$i+=$_&7;grep(vec($s,$i++,1)=1,1..($_>>3)-4);}}print"$s\n";

  14. #14
    Join Date
    Jun 2006
    Location
    Under your bed
    Posts
    357
    How did you guys gain confidence in your ability to write secure and efficient OOP code? Was it from reading books, taking classes, watching tutorials, or something else? When did you get to the point that you were pretty sure you could write code that would not be hacked and would not drain too many system resources?

  15. #15
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,614
    Quote Originally Posted by evenstar7139 View Post
    How did you guys gain confidence in your ability to write secure and efficient OOP code? Was it from reading books, taking classes, watching tutorials, or something else? When did you get to the point that you were pretty sure you could write code that would not be hacked and would not drain too many system resources?
    Much of security has little to do with OOP, but good use of OOP will mean that aspects of an app that you may determine could be potential security holes can be encapsulated within a given class/method. Then, by keeping your classes loosely coupled, you only have to worry about that particular security issue within that one class.

    I suppose the same would be true in terms of efficiency, in that critical parts of the app that have potential for being resource hogs can be centralized in their respective classes, so you only need to worry about optimization in a single place.

    As far as my personal "confidence", that mostly comes from practice, reading forums, practice, reading the book I referenced in my first reply, and, let's see...oh...yeah: practice.
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles