SitePoint Sponsor

User Tag List

Results 1 to 20 of 20
  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    63
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    help getting started on this subject!

    Hello,

    I'm writing a simple php+mysql online shop. I've made 3 successful php shops in the past, all using pretty much the same code, but it's not particularly fancy OOP (all the classes are just wrappers), but the code was starting to get messy and I've learnt a lot along the way.

    I'm making another shop, and this time I want to do it "properly". I don't want to make it a huge opensource project or anything, it will be a fairly small, but I think it's a great oppurtunity to learn how to do things properly! My database structure is suitably normalised I feel, it's just all the php stuff!

    I started off looking at other major open source php programs like phpbb3 for ideas on how to STRUCTURE the project (learnt about templates, which are great!), but now i'm getting bogged down in MVC, n-tiers, design patterns, table data gateways, and generally how to structure all the code, classes etc. Singleton classes, registry classes.....MVC seems kinda hardcore, are there alternatives?

    Of particular interest is how to get data from mysql database using classes. In the past I think i've been using a simple Table Data Gateway (I think), but these ideas are somewhat bewildering to get started with, and a problem I've always faced is how to deal with multiple rows from a product database...currently I just kind of wrap the php mysql functions....so i have:

    product->select_all()
    while (product->fetch()) {
    echo product->get_name();
    }
    .........
    and to select just one product
    product->select($id)
    product->fetch();
    echo product->get_name()
    .....

    I know this is a HUGE topic, but any tutorial links, or decent definitions to get me started would be great! Maybe a very general layout of how things should be structured.

    Many thanks for any help!

  2. #2
    SitePoint Member
    Join Date
    Feb 2008
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    a book

    I feel like I'm in roughly the same place as you. I just finished this book:
    http://www.manning.com/reiersol/

    I think it has a lot of good stuff to say about organizing a php project, and is very heavy on abstraction as a tool for organizing code and responsibilities.

    As with everything, we all need to decide for ourselves what's "right" for our situation.

  3. #3
    SitePoint Enthusiast
    Join Date
    Nov 2006
    Posts
    63
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    hi grossvogel,

    thanks for the suggestion, just downloaded the table of contents and it looks like a pretty nifty book!

  4. #4
    SitePoint Enthusiast
    Join Date
    Feb 2005
    Location
    Glasgow, Scotland
    Posts
    97
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    To get multiple rows you can have two classes, one called "ProductList" and one just called "Product".

    ProductList would do the query from the db for a list of products, and then create and store a Product object for each row returned. Then you would access them via the internal array in ProductList.

    I've always found that Singleton class for each type of "object" in your program is a lot more effective. Indeed, one of the "blueprint PHP applications" from Sitepoint was something called Eventum, a MySQL bug tracker developed by MySQL themselves.

    There almost all of their classes used the Singleton pattern and a class like User was basically a collection of all the functions to do with users on the site, and it was used like this:

    $user = User::getUserById($id);
    $template->assign(user_level, $user['user_level']);

    $userList = User::getUsers($options);
    $template->assign(users, $userList);


    I've did a lot of my projects in this style and it makes much more sense than creating Objects representing data that I only want to fetch and spit straight back out into a template.

  5. #5
    SitePoint Addict webaddictz's Avatar
    Join Date
    Feb 2006
    Location
    Netherlands
    Posts
    295
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Teeej View Post
    I've always found that Singleton class for each type of "object" in your program is a lot more effective.

    [...]

    I've did a lot of my projects in this style and it makes much more sense than creating Objects representing data that I only want to fetch and spit straight back out into a template.
    Oh noes, please don't.

  6. #6
    SitePoint Enthusiast
    Join Date
    Feb 2005
    Location
    Glasgow, Scotland
    Posts
    97
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I read more than enough unsupported opinions-passed-as-fact at University for my opinion to withstand a single blog post, but thanks for the link anyway.

    That post is especially awful though, when your article needs a heading labelled "What's the problem, again?" you really are clutching at straws. How is $user = User::getUserById($id) increasing coupling any more than $user = new User($id)?

  7. #7
    SitePoint Enthusiast
    Join Date
    Jun 2007
    Posts
    27
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Either you haven't read the article or your bias/pigheadedness renders insight impossible.

    There is a famous quotation I learned at university: None are so deaf as those that don't listen.

  8. #8
    SitePoint Enthusiast
    Join Date
    Feb 2005
    Location
    Glasgow, Scotland
    Posts
    97
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have a bias towards what? A Singleton class?

    You only have to read the comments to see the point I'm trying to make:

    You haven’t really shed any more light on the matter. I understand that complexity is a problem as an application grows in size, and that coupling is a common manifestation of complexity, but it’s not clear to me why a singleton, or other global data, should be uniformly avoided.

    You equivocate at the last minute when you admit that coupling is sometimes desirable and almost always unavoidable. That being the case the decision to employ the singleton pattern (or other global state) is transformed into a trade-off, and like many trade-offs there are all sorts of cases to be made for going either way.
    It's my opinion that a Singleton (or even just use a static class in PHP) can be beneficial when you have a simple web app which simply retrieves and spits out data from the database to a template. And you certainly don't have to sacrifice maintainability or introduce any of the problems that article attributes to Singleton use.


    If you read the feedback/comments on that article I'm not the only who agrees it is very poorly written and poorly supported.

  9. #9
    SitePoint Guru
    Join Date
    Dec 2005
    Posts
    982
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Teeej View Post
    There almost all of their classes used the Singleton pattern and a class like User was basically a collection of all the functions to do with users on the site, and it was used like this:

    $user = User::getUserById($id);
    $template->assign(user_level, $user['user_level']);

    $userList = User::getUsers($options);
    $template->assign(users, $userList);
    While I like using Singletons when needed, I don't like over using them like in your examples. I think that User::getUserById feels almost like procedural code where $user = new User($id); makes more sense. Also, why would the same manage single users and multiple users (as hinted by getUsers()). I think that a base class (User) should define the user and if multiple users are needed, a group wrapper would manage those (User_List). That abstracts the User as an "object" IMO.

    Granted I am very new to OOP and I actually started reading this topic because I am in the exact situation as the original poster. This is simply my $.02 based on what I feel OOP is meant to do.
    MySQL v5.1.58
    PHP v5.3.6

  10. #10
    SitePoint Enthusiast
    Join Date
    Jun 2007
    Posts
    27
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Teeej View Post
    It's my opinion that a Singleton (or even just use a static class in PHP) can be beneficial when you have a simple web app which simply retrieves and spits out data from the database to a template. And you certainly don't have to sacrifice maintainability or introduce any of the problems that article attributes to Singleton use.


    If you read the feedback/comments on that article I'm not the only who agrees it is very poorly written and poorly supported.
    I dont think the article is poorly supported, it's just that people dont like what kyber is saying. I attribute this to the procedural roots of most php programmers who on the one hand want to code OOP but on the other hand still think in procedural terms.

    What you are saying in the quote is actually pure pragmatism, but we are not talking about pragmatic issues but rather about theoretical, almost idealistic ones.
    It is evident that in a "simple web application" - like you call it - a singleton is definetely the most convenient and best fitting option. I would even dare to say that for a simple web application procedural code is - from a pragmatic perspective - the best choice, since you need the least effort for achieving your goal (the simple web app).
    But now abstract from this example and think about extensibility and reusability of your application. I wont mention the benefits of OOP, since they are widely approved. However, think about your singletons and other static classes. They are - as the name says - static and in theory static is always bad, because we want to achieve flexibility and reusability. Static calls are always inflexible, as they cause compile-time coupling.
    Singletons in particular hide dependencies (they are not visible in the interface of your class), cause tight coupling between your classes and mix up responsibilities, since a class should neither care nor know whether it is a singleton or not.

    Singletons are definetley useful and convenient for simple applications, but they are theoretically evil, because ultimately their negative aspects will prevail.

  11. #11
    SitePoint Enthusiast
    Join Date
    Feb 2005
    Location
    Glasgow, Scotland
    Posts
    97
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by BrandonK View Post
    While I like using Singletons when needed, I don't like over using them like in your examples. I think that User::getUserById feels almost like procedural code where $user = new User($id); makes more sense. Also, why would the same manage single users and multiple users (as hinted by getUsers()). I think that a base class (User) should define the user and if multiple users are needed, a group wrapper would manage those (User_List). That abstracts the User as an "object" IMO.

    Granted I am very new to OOP and I actually started reading this topic because I am in the exact situation as the original poster. This is simply my $.02 based on what I feel OOP is meant to do.
    Of course that is what OOP is meant to do, and I offered that exact solution in the post you quoted:
    To get multiple rows you can have two classes, one called "ProductList" and one just called "Product".
    But if all you're doing is fetching rows from a database and spitting them straight out at the user, it's alot of complexity to achieve a very simple thing.

    I feel that a lot of the OO principals just don't apply to simple web apps, and people can lose sight of the real benefit by trying to make these principals work where they aren't needed.

    My apps don't use static classes or singletons exclusively, mostly just for representing the tables in a database that I need to store and fetch info from (which happens to be a major part of most web apps).

  12. #12
    SitePoint Enthusiast
    Join Date
    Feb 2005
    Location
    Glasgow, Scotland
    Posts
    97
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by myc View Post
    I dont think the article is poorly supported, it's just that people dont like what kyber is saying. I attribute this to the procedural roots of most php programmers who on the one hand want to code OOP but on the other hand still think in procedural terms.
    My introduction to programming was 4 years of Java at University, so I dont fit that bill at all. I would attribute the negative feedback to the fact that he has stated why using Singleton is bad without actually showing why using a Singleton causes it. This is something in my experience that many proponents of pure OO are guilty of, almost as if pure OO makes sense to them and seems like a great idea so let's just say it is despite actual factual and empirical evidence to back it up.

    It is evident that in a "simple web application" - like you call it - a singleton is definetely the most convenient and best fitting option. I would even dare to say that for a simple web application procedural code is - from a pragmatic perspective - the best choice, since you need the least effort for achieving your goal (the simple web app).
    But now abstract from this example and think about extensibility and reusability of your application.
    As I stated already, Eventum uses static classes extensively and it extensive reuseable. It is also highly maintainable, much more so than any of the open source MVC software I've tried to work with.

    I wont mention the benefits of OOP, since they are widely approved. However, think about your singletons and other static classes. They are - as the name says - static and in theory static is always bad, because we want to achieve flexibility and reusability. Static calls are always inflexible, as they cause compile-time coupling. Singletons in particular hide dependencies (they are not visible in the interface of your class), cause tight coupling between your classes and mix up responsibilities, since a class should neither care nor know whether it is a singleton or not.
    Using Singleton or static classes absolutely does not prevent your classes from being reuseable or flexible. Again all you're doing is telling me they are without showing me the limitations with real examples.

    I reuse all my Singleton classes, so does the Eventum software. And I reuse mine across individual projects and multiple projects.

    Basically it comes down to: if used improperly or abused then Singleton is "bad". But so is every practice or technique in software engineering.

  13. #13
    ********* Victim lastcraft's Avatar
    Join Date
    Apr 2003
    Location
    London
    Posts
    2,423
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hi...

    How do you unit test code with Singletons? How do you test code that calls static methods?

    yours, Marcus

    p.s. By Singleton I assume you mean the...
    PHP Code:
    MyClass::instance() 
    ...variety. If you mean just creating one of...
    PHP Code:
    new MyWrapperForMyTable() 
    ...then that's a TableGateway pattern, which is very different.
    Marcus Baker
    Testing: SimpleTest, Cgreen, Fakemail
    Other: Phemto dependency injector
    Books: PHP in Action, 97 things

  14. #14
    SitePoint Enthusiast
    Join Date
    Jun 2007
    Posts
    27
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    After having a brief look at Eventum I must say its very poorly written OOP, since it is actually more a collection of single functions grouped by classes. This code is definetely not flexible, as the extensive use of static functions renders many features of OOP impossible (e.g. inheritance, static calls are always binded to a specific class). Moreover, dependencies are very hard to detect, since the interface of the class doesn't tell them (also a result of the enormous usage of static calls).

    Code like this (excerpt from eventum)
    PHP Code:
    function update()
            {
                if (
    Validation::isWhitespace($_POST["title"])) {
                     return -
    2;
            }
                 if (
    Validation::isWhitespace($_POST["message"])) {
                return -
    3;
                }
                
    $stmt "UPDATE
                             " 
    APP_DEFAULT_DB "." APP_TABLE_PREFIX "news
                     SET
                        nws_title='" 
    Misc::escapeString($_POST["title"]) . "',
                        nws_message='" 
    Misc::escapeString($_POST["message"]) . "',
                            nws_status='" 
    Misc::escapeString($_POST["status"]) . "'
                          WHERE
                        nws_id=" 
    Misc::escapeInteger($_POST["id"]);
                 
    $res $GLOBALS["db_api"]->dbh->query($stmt);
                 if (
    PEAR::isError($res)) {
                    
    Error_Handler::logError(array($res->getMessage(), $res->getDebugInfo()), __FILE____LINE__);
                     return -
    1;
                } else {
                    
    News::removeProjectAssociations($_POST['id']);
                    foreach (
    $_POST['projects'] as $prj_id) {
                        
    News::addProjectAssociation($_POST['id'], $prj_id);
    }
                     return 
    1;
                 }
             } 
    is just a perfect example of what I said before, code pretending to be OOP but actually being good old procedural one. (sorry couldnt format the code properly at work)
    If you want to tell me that code is the best solution in terms of flexibility and reusability then you haven't understand anything of OOP. (no offense)

  15. #15
    SitePoint Enthusiast
    Join Date
    Feb 2005
    Location
    Glasgow, Scotland
    Posts
    97
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm not using Eventum as a great example of OOP, just a good example of a maintainable and widely used application that uses some aspects of OOP (i.e the relevant ones) to build a better solution than pure procedural. My point when I suggested using Singleton/static classes instead of pure OOP principals was that I just don't think most of the principals of OOP translate all that well to the data and behaviour requirements of your typical web app.

    Using the code you posted as an example, I'm trying to figure out how reusable and flexible a class that updates a specfic table (news) in a specific database (hosting eventum) has to be.

  16. #16
    SitePoint Enthusiast
    Join Date
    Feb 2005
    Location
    Glasgow, Scotland
    Posts
    97
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by lastcraft View Post
    How do you test code that calls static methods?
    Heh, probably the same way the vast majority of development teams test their non-OOP websites right now.

  17. #17
    SitePoint Enthusiast
    Join Date
    Jun 2007
    Posts
    27
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Teeej View Post
    I'm not using Eventum as a great example of OOP, just a good example of a maintainable and widely used application that uses some aspects of OOP (i.e the relevant ones) to build a better solution than pure procedural.
    Eventum uses classes to group their functions, there is no further aspect of OOP Eventum uses and therefore there is absolutely no difference between the above posted code and procedural one.

  18. #18
    SitePoint Enthusiast
    Join Date
    Feb 2005
    Location
    Glasgow, Scotland
    Posts
    97
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Actually, they use proper objects for their DB and Template APIs. It's a mash-up of different styles.

    Out of interest, are there any projects where you can view the source (for free) which are pure OO?

    Edit - http://www.sitepoint.com/blogs/2006/...p-application/ - the original article that raised my attention to Eventum

  19. #19
    ********* Victim lastcraft's Avatar
    Join Date
    Apr 2003
    Location
    London
    Posts
    2,423
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hi...

    Quote Originally Posted by Teeej View Post
    Heh, probably the same way the vast majority of development teams test their non-OOP websites right now.
    Sadly, most of them don't. Or they employ manual testers. Or they single step through the debugger . Some people like banging nails in with their fist, but I'd rather use a hammer. Ignorance is not always bliss.

    Such a waste of a good paradigm .

    yours, Marcus
    Marcus Baker
    Testing: SimpleTest, Cgreen, Fakemail
    Other: Phemto dependency injector
    Books: PHP in Action, 97 things

  20. #20
    SitePoint Guru dagfinn's Avatar
    Join Date
    Jan 2004
    Location
    Oslo, Norway
    Posts
    894
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by lastcraft View Post
    Hi...

    How do you unit test code with Singletons? How do you test code that calls static methods?

    yours, Marcus

    p.s. By Singleton I assume you mean the...
    PHP Code:
    MyClass::instance() 
    ...variety. If you mean just creating one of...
    PHP Code:
    new MyWrapperForMyTable() 
    ...then that's a TableGateway pattern, which is very different.
    I'm not a fan of singletons, but testing them is actually not that bad. The singleton has to have a method to set the instance so that you can replace it for testing:
    PHP Code:
    MyClass::load($instance
    This is not much more cumbersome than testing normal objects.

    Static methods are hell to test, unless they are implemented internally as calls to this kind of loadable singleton instance.
    Dagfinn Reiersøl
    PHP in Action / Blog / Twitter
    "Making the impossible possible, the possible easy,
    and the easy elegant"
    -- Moshe Feldenkrais


Bookmarks

Posting Permissions

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