SitePoint Sponsor

User Tag List

Page 1 of 4 1234 LastLast
Results 1 to 25 of 87
  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2009
    Posts
    81
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Do you prefer writing libraries as classes, or simply a collection of functions?

    I used to use classes mostly for libraries, but as I've gotten more comfortable/in love with OOP, I'm starting to think that I should reserve classes for objects only. Now I know there's no rule stating this, but it just seems to make sense. I would usually call the functions as static methods of the class, but since I tend to write descriptive function names this resulted in a lot of typing . The only clear benefit I see to using classes for libraries is the organization they provide. Am I missing something? What are your thoughts on this?

  2. #2
    SitePoint Addict
    Join Date
    Sep 2005
    Posts
    335
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I prefer to write libraries as functions unless they benefit from I'm with you. Classes for objects, libraries are functions.
    PHP Shopping Cart Software Easy Ecommerce Shopping Cart Script.
    PHP Super Cart is 100% template driven.

  3. #3
    SitePoint Guru
    Join Date
    Jan 2005
    Location
    heaven
    Posts
    953
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Arrrms View Post
    I used to use classes mostly for libraries, but as I've gotten more comfortable/in love with OOP, I'm starting to think that I should reserve classes for objects only.
    I don't get what your trying to say since objects are the instantiation of classes... So reserving classes for objects is simple restating it's purpose making one big circle.

    Quote Originally Posted by Arrrms View Post
    Now I know there's no rule stating this, but it just seems to make sense. I would usually call the functions as static methods of the class, but since I tend to write descriptive function names this resulted in a lot of typing .
    You probably could save some typing by refactoring and applying a couple handy design patterns.


    Quote Originally Posted by Arrrms View Post
    The only clear benefit I see to using classes for libraries is the organization they provide. Am I missing something? What are your thoughts on this?
    There are plenty of reasons for OOP. But the reason I stick to OOP paradigms are it can make very complex algorithms rudimentary and provide a simple way of consolidating and packaging code that can be reused often.
    Creativity knows no other restraint than the
    confines of a small mind.
    - Me
    Geekly Humor
    Oh baby! Check out the design patterns on that framework!

  4. #4
    SitePoint Enthusiast
    Join Date
    Jan 2009
    Posts
    81
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by imaginethis View Post
    I don't get what your trying to say since objects are the instantiation of classes... So reserving classes for objects is simple restating it's purpose making one big circle.
    What I meant is that I'm reserving classes only for pieces of code that can be though of as (real life) objects (e.x.: a row in the DB)

    Quote Originally Posted by imaginethis View Post
    There are plenty of reasons for OOP. But the reason I stick to OOP paradigms are it can make very complex algorithms rudimentary and provide a simple way of consolidating and packaging code that can be reused often.
    So far, the consolidation is the only benefit I see to using classes for libraries.

  5. #5
    Use The Cloud
    Join Date
    Jan 2006
    Location
    Boise, ID
    Posts
    556
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What about faster development?

    Loading functions manually seems annoying. With classes autoloading makes it easy to handle dependencies.
    Brad Hanson, Web Applications & Scalability Specialist
    ► Is your website outgrowing its current hosting solution?
    ► PM me for a FREE scalability consult!
    ► USA Based: Available by Phone, Skype, AIM, and E-mail.

  6. #6
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,151
    Mentioned
    16 Post(s)
    Tagged
    3 Thread(s)
    Generally a class should be a noun but it isn't a hard and fast rule.

  7. #7
    SitePoint Enthusiast
    Join Date
    Jan 2009
    Posts
    81
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I forgot about autoloading, bhanson - great point.
    In my framework right now I load (through a config file) all the libraries I think are essential for most apps. I still need to add a function to load a specific library, and although it's not a big hassle, it's not as convenient as autoloading a class

  8. #8
    SitePoint Wizard
    Join Date
    Mar 2008
    Posts
    1,149
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP 5.3 is almost out (in theory...), so maybe that will solve your dilemma.

    Though I don't think that there's any facility to autoload namespaces.

  9. #9
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I still prefer using functions. I hate it when I see a class with loads of static functions in it, and nothing else - just seems like an abuse of OOP to me. An object/class is supposed to represent an entity, and all related properties and methods, it's not just simply a way of grouping all your functions together. It's not hardship to include a functions file in an init/bootstrap file either really, and all this stuff about 'polluting the global namespace' is complete rubbish, a class with static methods is just as much in the global namespace as a function.

  10. #10
    SitePoint Guru
    Join Date
    Jan 2005
    Location
    heaven
    Posts
    953
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Arrrms View Post
    What I meant is that I'm reserving classes only for pieces of code that can be though of as (real life) objects (e.x.: a row in the DB)
    That seems some what crude to be honest and I don't really see how that would work in many cases and I wouldn't lend myself to such harsh distinctions. You never know how or if your code written for one purpose could be, after some refactoring, applied to solve some other problem.

    Quote Originally Posted by Stormrider View Post
    I still prefer using functions. I hate it when I see a class with loads of static functions in it, and nothing else - just seems like an abuse of OOP to me. An object/class is supposed to represent an entity, and all related properties and methods, it's not just simply a way of grouping all your functions together. It's not hardship to include a functions file in an init/bootstrap file either really, and all this stuff about 'polluting the global namespace' is complete rubbish, a class with static methods is just as much in the global namespace as a funciton.
    Thats not OOP. That's miss using classes as over-glorified namespaces.
    Creativity knows no other restraint than the
    confines of a small mind.
    - Me
    Geekly Humor
    Oh baby! Check out the design patterns on that framework!

  11. #11
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Well, exactly my point

  12. #12
    PHP/Rails Developer Czaries's Avatar
    Join Date
    May 2004
    Location
    Central USA
    Posts
    806
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Arrrms View Post
    The only clear benefit I see to using classes for libraries is the organization they provide. Am I missing something? What are your thoughts on this?
    One of the major benefits to OOP that I really don't see a lot of people ever talking about is the idea of responsibility that objects provide. For me, this is one of the main keys to understanding how OOP works and how you should think about it. So when you create an 'Email' class, that class is only ever responsible for doing things related to building and sending emails. A table row class would only be responsible for actions related to that one specific row (not other database tables, rows, queries, etc). The goal as you go along is to isolate dependencies and make objects as dumb as possible, so that they only serve one purpose - a limited set of responsibilities. You can keep yourself in-check by continuing to ask questions like:
    - "What is the responsibility of this object?"
    - "Is this object doing too much?"
    - "Can I separate functionality into other objects where it might make more sense?"
    - "Have I made sure to expose all hidden dependencies (i.e. pass them in the constructor instead of 'global' ones)?"

    So there is much much more to OOP (classes in code) than you're giving it credit for. It's not just a fancy way of grouping common functionality together - it's a whole new way of thinking about your code.

  13. #13
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Absolutely, but that isn't what is being talked about - we are talking about libraries of functions, not specific tasks like email etc, which should of course be in a class.

  14. #14
    SitePoint Evangelist
    Join Date
    Mar 2006
    Location
    Sweden
    Posts
    451
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Could someone give an example of such a library function that is so simple it won't benefit from being inside a class?

  15. #15
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
     function redirect ($strURL) {
      
    session_write_close();
      
    header('Location: ' trim($strURL));
      exit();
     }
    //function

     
    function isempty ($strValue) {
      
    //Used to get round the fact that PHP won't let you use anything but scalar variables in empty()

      
    return empty($strValue);
     }
    //function

     
    function formatAsParagraphs ($strInput$intSpacing 0) {
      
    $strSpacing str_repeat(" "$intSpacing);

      
    $strInput trim($strInput);
      
    $strInput "<p>" str_replace("\r\n\r\n""</p><p>"$strInput) . "</p>";
      
    $strInput str_replace("</p><p>""</p>\r\n\r\n<p>"$strInput);
      
    $strInput str_replace("\r\n""\r\n" $strSpacing$strInput);
      
    $strInput wordwrap($strInput120"\r\n" $strSpacing);

      return 
    $strSpacing $strInput;
     }
    //function

     
    function getDBConn () {
      static 
    $dbConn;

      if (
    isempty($dbConn)) {
       
    $dbConn = new DBmySQLi(DATABASE_HOSTDATABASE_USERDATABASE_PASSDATABASE_NAME);
      }
    //if

      
    return $dbConn;
     }
    //function 

  16. #16
    SitePoint Evangelist
    Join Date
    Mar 2006
    Location
    Sweden
    Posts
    451
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't think I agree with that those functions are so basic that they never will evolve and benefit from being inside a class which you instantiate, especially not the redirect and getDBConn functions. formatAsParagraphs would benefit being inside a view helper class, since you could use different helpers depending on the context. Sometimes, you'd might want to add a class to the paragrahs, other times you'd might want to decorate the html with some elements. To have that kind of conditional logic inside a function would most likely become a mess. And I don't really get why you would need the isempty() function? It's perfectly legal to pass a scalar, an array or an object to empty().

  17. #17
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Scalar is the wrong word, I mean variable. You cannot pass the results of a function to it. Eg:

    PHP Code:
    if (empty($objBasket->getProducts())) { 
    ...is not possible. And from the php docs, neither is:

    PHP Code:
    if (empty(trim($var))) { 
    With isempty or whatever, you can.

    Those functions are from an old site that doesn't use view helpers or anything like that, but I fail to see why redirect would end up in a class?

    I don't like this obsession with trying to over-abstract everything, and trying to put everything in a class, even when it isn't necessary.

  18. #18
    SitePoint Evangelist
    Join Date
    Mar 2006
    Location
    Sweden
    Posts
    451
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah, I see your point. But while that's true, empty($var) is the same as !$var, so you could do: if(!$objBasket->getProducts()).

    Well, the redirect function deals with adding an http header in the response, which is something you'd probably want to do centralize in some sort of http response object to make sure that you send all headers together at first, and then send the content. We all remember those "headers already sent" errors you got when you just got into web development.

  19. #19
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by wysiwyg View Post
    empty($var) is the same as !$var, so you could do: if(!$objBasket->getProducts())
    Personally I can't stand code that misuses typing. The ! is used to flip a boolean - i.e. true === !false.

    So if(!$var) is like saying "if the opposite of nothing is equal true".

    It may work in practise, but the theory behind it is... well it feels unstable. You'd never see it in stricter languages - and personally I keep my code as strict as possible.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  20. #20
    SitePoint Evangelist
    Join Date
    Mar 2006
    Location
    Sweden
    Posts
    451
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Really? How is:
    if (empty($objBasket->getProducts())) {
    different from
    if (!$objBasket->getProducts()) {
    ?

    EDIT:
    Hmm, misuses typing? I guess that depends on how you define the "correct" way to handle types, but since "if(!$var)" is perfectly legal in PHP, I can't see how it would be "misusing typing"? If you want strictness, why not use a strictly typed language, such as Java?

  21. #21
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Really? How is:
    if (empty($objBasket->getProducts())) {
    different from
    if (!$objBasket->getProducts()) {
    ?
    Though I wasn't aware that this, programmatically it is exactly the same. In which case it's just a difference in mental logic - i.e. use what you prefer

    I prefer to use functions which are suited to the exact job - i.e. my functions return false in situations where data isn't available or correct, and use strict comparisons on false to make sure it's not just a variable that could be loosely equal to false.

    As for the above example, I'd use:
    PHP Code:
    $Products $Basket->GetProducts();
    if(
    $Products === false){
        
    //Handle the issue
    }else{
        if(
    Count($Products) > 0){
            
    //Display Products
        
    }else{
            
    //Do something else
        
    }

    If you want strictness, why not use a strictly typed language, such as Java?
    I do - just not for the web
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  22. #22
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    The documentation for empty() tells you the differences between that and casting to boolean.

    empty will not throw a warning if a variable you pass to it isn't set, but using !$var will, so they are not programatically the same.

    It's readablity as well - 'Is this equal to false' isn't the same thing as 'Is this empty' - it's a lot easier to see the intentions of the programmer when you use things like empty() instead of using 'shortcuts', or things that just work anyway.

  23. #23
    SitePoint Evangelist
    Join Date
    Mar 2006
    Location
    Sweden
    Posts
    451
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arkinstall View Post
    Though I wasn't aware that this, programmatically it is exactly the same. In which case it's just a difference in mental logic - i.e. use what you prefer
    Actually you were right, it isn't exactly the same, but it's very similar. If you do: if(!$var) and $var hasn't been set, that generates a warning, while if(empty($var)) doesn't.

    Stormrider:
    You can get around it by using ! for method calls ("if(!$obj->get())"), and empty() for variables. That way, you don't need your isempty() function.

    Quote Originally Posted by arkinstall View Post
    I do - just not for the web
    Why not? You seem to like static typing better, so JSP would probably be a better fit for you?
    PHP is a dynamically typed language, and not using the strengths of it because you prefer static typing seems kind of odd.

  24. #24
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by wysiwyg View Post
    Stormrider:
    You can get around it by using ! for method calls ("if(!$obj->get())"), and empty() for variables. That way, you don't need your isempty() function.
    I like consistency in my code. You are inventing lots of ways to get round the need for this, then get round the fact that it doesn't work in certain situations, when surely my solution is a lot easier? All this trouble for 3 lines of code which make it more consistent and more readable?

  25. #25
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Stormrider View Post
    PHP Code:
     function isempty ($strValue) {
      
    //Used to get round the fact that PHP won't let you use anything but scalar variables in empty()

      
    return empty($strValue);
     }
    //function 
    This has very little to do with the original question, but that function is completely pointless. empty is a language construct in php that specifically won't raise an error if a variable isn't set. Putting it inside a function like that, completely counters that feature, since you would then get a warning when calling the wrapping function on a undefined variable. FWIW, I find empty a weird concept in the first place. If you don't know if a variable is set or not, then I think that is a sign of problems with your code, that you should fix instead. As it happens, I'm guessing you feel the same way, because if you had indeed had undefined variables, then you would have realised that your function doesn't work.


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
  •