Re: [PHP] OOP slow -- am I an idiot?
Stut wrote: This is a question of design, not a question of whether to use OOP. For example, in several of the sites I maintain I have classes that inherit from a base class called Table. The base class provides a lot of the basic methods for working on a table (think ActiveRecord). It also has static methods for doing things like updates and deletes based on a where clause. The derived classes can override filter methods (AfterLoad and BeforeSave) to massage the data after it's loaded and before it's saved. They also add any methods needed for acting on that particular entity. I'm the first to admit that OOP is not always the best methadology to use - the 'best methadology for all situations' does not exist. However, the general feeling people will get towards OOP from this list seems to be 'OOP bad, anything else better'. OOP is great as long as you follow OOD principles and have a fair amount of common sense. It should not be used just because it's there, but it should also not be dismissed. In fact, in writing that I've just realised that OOP is not the key... OOD is. OOD can be applied (with no syntax or compiler assistance) in a functional system which will have great benefits, all of which I think most people are aware of but, for whatever reason, fail to adequately apply - which is where OOP can be useful since it enforces the structure and protection through the syntax (PHP4 sucked for this, PHP5 is better). When you actually think about it, OOP is not a methadology - it's a syntax. OOD is the methadology. Ramble... ramble... ramble... over! I know this is a fairly old thread, but I thought people might be interested in reading a write-up I've recently finished regarding my Table class and it's usage. I had been intending to write it for a while, but a request from Ed Lazor kicked me into actually doing it. Don't expect the quality to be too high - I'm more used to writing requirement/functional specs and user documentation than this type of thing. http://stut.net/articles/php_models.html All comments are welcome, both on the article and on the code itself. However, please keep on-list replies to the code! -Stut -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Stut [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Tony Marston wrote: Stut [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] My general approach to designing a system is data-centric. I tend to start by defining the database schema since getting that clear in my head tends to lead me to a decent design. What a coincidence! That's exactly my approach, but I've taken it one step further. I always start with a properly normalised database which I can then import into my daa dictionary application. From there I can press a button and create a class file for each database table, and I am ptting the finishing touhes to a procedure whereby I can press another button to generate the scripts which will maintain each table. This means I can get basic transactions up and running without writing a single line of code. All I have to do is edit these files to include business logic and any customisations. This level of automation is not possible with some people's OO implementations, so I can only conclude that their approach is not the optimal one. Youch!! Your implementation seems to be focused on development efficiency rather than runtime efficience. Precisely. That is why I said it was adminstrative web applications which typically have far fewer users than web sites. In all but rare research projects this is backwards for a web-based system. Wrong again. This is for administrative web applications, the type that were previously built as desktop applications. Their function is to get data into and out of a database i.e. CRUD applications), not to serve thousands of casual vuisitors. This is exactly the practice I am trying to discourage. It's a well-known fact that code generators are a poor substitute for real developers. It depends how you go about it. My code generators fulfil the basics, then the programmer's job is to customise it. For most projects I don't start out with OOP in mind, but my brain is used to building OOP-style systems so nearly everything I do ends up with a few classes. The difference with me is that I don't waste my time with trivial websites, I concentrate on administrative web applications. But even when I wrote the code for my own website at http://www.radicore.org I still used all my database classes as it was far easier than doing it the traditional old-fashioned way Trivial websites are where you can get away with using code generators. For anything non-trivial I would not feel comfortable with a jack-of-all-trades-master-of-none-style of code. Now that I think of it I'm quite anal about the quality of my code, so I don't think I'd ever use a code generator - never have before. I have never liked any of the code generators I have seen created by others, but with my general-purpose framework I noticed that a lot of the code that I was generating by hand followed a familiar pattern. It was then a simple exercise to write a program to generate this same code on command. Be aware that I am not attempting to generate *all* the code that an application will need, just the basics to get it functioning. This takes all the drudgery out of the job and leaves the programmer to do the interesting bits. -- Tony Marston http://www.tonymarston.net http://www.radicore.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Stut [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Ed Lazor wrote: On Oct 12, 2006, at 4:36 PM, Stut wrote: If I then go on to create an admin interface for the users, I would create another completely separate class called UserCollection to handle more than one user. I may at that point choose to expose any data-massaging methods in User to UserCollection to avoid code duplication, but that would be the extent of the way UserCollection uses the User class since the User class is optimised to work on a single user at any one time. We use a similar approach for the user class. I haven't ever implemented something like the UserCollection class though. I'm curious about that. Does your UserCollection class extend the basic user class? Or is it something else entirely; I dunno, maybe UserCollection has a property defined as an array of User class? I think that's what people were saying earlier in the thread as being a very bad thing in terms of memory utilization, etc. Indeed, that would be a very bad thing, unless you've already considered that. I've previously mentioned that I have an ActiveRecord-style implementation for a lot of my DB access. The base class for that system has a static function called FindAll which will return an array of objects. However, it only does a single SQL statement. The base class also has a method LoadFromArray which, shockingly, loads the object from an array. This means that from a single DB request I can get an array of objects each representing one entitity (potentially a row, but not necessarily). The very idea of one object per row makes me want to throw up. I have one object per table, and each object can deal with any number of rows. I don't use getters and setters to access the columns from any row, I simply input an array (typically one row from the $_POST array) and output an array which may contain any number of rows. I find this to be far easier and no less efficient. -- Tony Marston http://www.tonymarston.net http://www.radicore.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Ed Lazor [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Oct 13, 2006, at 1:35 AM, Tony Marston wrote: What a coincidence! That's exactly my approach, but I've taken it one step further. I always start with a properly normalised database which I can then import into my daa dictionary application. From there I can press a button and create a class file for each database table, and I am ptting the finishing touhes to a procedure whereby I can press another button to generate the scripts which will maintain each table. This means I can get basic transactions up and running without writing a single line of code. All I have to do is edit these files to include business logic and any customisations. Is the Radicore framework still available? What do you mean *still*? Since I released it I have never closed it down. I am still working on it and releasing improvements. I am just about to release some new functionality which will generate more standard code for each transaction. Watch my website (see link in my signature) for an announcement. -- Tony Marston http://www.tonymarston.net http://www.radicore.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Ed Lazor [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Oct 13, 2006, at 1:54 AM, Stut wrote: Youch!! Your implementation seems to be focused on development efficiency rather than runtime efficience. In all but rare research projects this is backwards for a web-based system. This is exactly the practice I am trying to discourage. It's a well-known fact that code generators are a poor substitute for real developers. I agree with Stut, but I'd also like to check out a copy of the framework. It seems like a lot of people are using frameworks now days and I can't help but wonder if they provide similar performance as the OOP library that Stut uses. If you want to build administrative web applications which have a small number of users, and where development costs are more important than performance of execution (i.e. developer cycles over cpu cycles) then check out RADICORE at http://www.radicore.org It is better than Ruby on Rails. -- Tony Marston http://www.tonymarston.net http://www.radicore.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Please include the list when replying to that others may benefit (or suffer) from the discussion. Bruce Cowin wrote: I like your static user class. Does the user instance then get saved to a session variable that is serialized/unserialized on every page? There is no user instance as such. In that simple case the only thing stored is an array of allowable actions. If I were to extend it to more complex user system I would likely convert the User class to non-static and store an instance of that in the session. I would then have a static method called Current() to return the static instance. -Stut -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Ed Lazor wrote: On Oct 12, 2006, at 4:36 PM, Stut wrote: If I then go on to create an admin interface for the users, I would create another completely separate class called UserCollection to handle more than one user. I may at that point choose to expose any data-massaging methods in User to UserCollection to avoid code duplication, but that would be the extent of the way UserCollection uses the User class since the User class is optimised to work on a single user at any one time. We use a similar approach for the user class. I haven't ever implemented something like the UserCollection class though. I'm curious about that. Does your UserCollection class extend the basic user class? Or is it something else entirely; I dunno, maybe UserCollection has a property defined as an array of User class? I think that's what people were saying earlier in the thread as being a very bad thing in terms of memory utilization, etc. Indeed, that would be a very bad thing, unless you've already considered that. I've previously mentioned that I have an ActiveRecord-style implementation for a lot of my DB access. The base class for that system has a static function called FindAll which will return an array of objects. However, it only does a single SQL statement. The base class also has a method LoadFromArray which, shockingly, loads the object from an array. This means that from a single DB request I can get an array of objects each representing one entitity (potentially a row, but not necessarily). Bear in mind that this is not always the best solution (as ever). Continuing the example from my previous email, I very much doubt that the UserCollection class would contain any instances of the User class. However, if you read back I did say that I would probably expose the methods in the User class to massage the data, meaning that any part of the data in the database that needs transforming before it can be used is handled by one piece of code whether it's for single or multiple records. How to properly define the User class and UserCollection classes also seems to delve into issues of UML and CORBA, which I don't have a lot of experience with. Is anyone applying those technologies to PHP? It's rare for me to use any formal system for defining my object model, but when I do it's usually UML. If I remember correctly from my degree, CORBA is a remoting specification so I'm not sure how it applies here. This makes it perfect for an object-per-record implementation since there is only one record. Yea, but I keep thinking back to how the implementation of data representation is separate from the implementation of how that data is used. Going back to the users example, I created a User class. I never bothered to create a UserCollection class because coding that does anything with a collection of users typically ends up being situational. Say I want a list of customers. I could create a UserCollection class with a method called list... and I could have it query the db and dump general fields. That seems like a fairly generic approach, so it might work, but I usually want to do something with individual fields - like link to a specific webpage to view more information on the customer, edit the customer record, delete, etc.. I know I could code all of these features into the class... but it reaches the point where it seems like overkill. It seems better to just create a webpage that has code to handle that which is what I end up doing. Mind you, I once created a bunch of classes that did all of the cool pretty formatting, table layout, with customizable doohikies, but that's where the classes started getting bloated, the system started bogging down, and there were very small, but very noticeable, delays in loading pages. I guess that leads me back to wondering how you implemented the UserCollection class or, at least, what features you built into it in order for it to be of benefit. I'm also assuming (uhoh hehe) that the same thing applies to other object hierarchies - for example, one class that defines a product and another class that defines a collection of products wondering how the two would be implemented to maintain efficiency... and I'm guessing your answer is that how you implement it depends on the situation... whether the site focuses on using individual products the most or ends up working with collections of products most... but it seems like it wouldn't matter... ie. again, the separation of data from implementation. Situational - that's a term I've never heard in this context before. To me what you're describing is evil. I use OOP to wrap data such that I can access it in a consistent manner from anywhere. The only SQL I ever write is in classes. While it's true that I could do everything I do with OOP functionally, using OOP forces me to think about how data and operations on data are connected. Having said
Re: [PHP] OOP slow -- am I an idiot?
On 10/13/06, Stut [EMAIL PROTECTED] wrote: Ed Lazor wrote: ...Or is it something else entirely; I dunno, maybe UserCollection has a property defined as an array of User class? I think that's what people were saying earlier in the thread as being a very bad thing in terms of memory utilization, etc. I'm honestly having a difficult time thinking of any way *other* than having an array of User objects. In previous projects I've tried the route of (like Richard mentioned early on): class Customers { var $ids = array(); var $names = array(); } But found it very cumbersome and unintuitive when dealing with a single Customer. Moreso I got lost when I didn't know if I were dealing with one or many customers... As soon as I went to a Customer and CustomerCollection approach, I was able to make sense of it all. Even though CustomerCollection usually didn't actually exist, except conceptually as an array of Customer objects within my application code. Like Stut suggested, I too have static fetch functions derived from the base ActiveRecord class that return arrays of objects. Maybe all of my applications have been simple enough in that I tended to work on single objects 95% of the time, and therefore creating interfaces for those single objects made sense. I think that's what Ed means by situational? It is occuring to me that perhaps all of my bias is centered around the fact that I always create my models as children of an ActiveRecord class, which is by nature based on *one record* of a table. Is there an ActiveTable class that, if implemented, might completely change everything??? Until then, I'm not convinced: constructing a basic building block such as a Customer, and then an aggregate block such as a collection of Customers, and so on, seems the most stable and scalable approach almost without exception...and perhaps, with that, I'm revealing the extent of my OOP naivety... John W -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
On Oct 13, 2006, at 1:35 AM, Tony Marston wrote: What a coincidence! That's exactly my approach, but I've taken it one step further. I always start with a properly normalised database which I can then import into my daa dictionary application. From there I can press a button and create a class file for each database table, and I am ptting the finishing touhes to a procedure whereby I can press another button to generate the scripts which will maintain each table. This means I can get basic transactions up and running without writing a single line of code. All I have to do is edit these files to include business logic and any customisations. Is the Radicore framework still available? -Ed -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
On Oct 13, 2006, at 1:54 AM, Stut wrote: Youch!! Your implementation seems to be focused on development efficiency rather than runtime efficience. In all but rare research projects this is backwards for a web-based system. This is exactly the practice I am trying to discourage. It's a well-known fact that code generators are a poor substitute for real developers. I agree with Stut, but I'd also like to check out a copy of the framework. It seems like a lot of people are using frameworks now days and I can't help but wonder if they provide similar performance as the OOP library that Stut uses. -Ed -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
# [EMAIL PROTECTED] / 2006-10-12 06:49:22 +0100: Roman Neuhauser wrote: # [EMAIL PROTECTED] / 2006-10-11 21:28:36 +0100: Richard Lynch wrote: This is a classic example of the obvious OOP solution being wildly inappropriate. Ok, so I now find myself in the unusual position of disagreeing with the Lynchmeister. Why is this wildly inappropriate? IMHO this is what OOP is all about. [...] I never said anything about physical entities. The OOP methodology has nothing to do with physical entities, but it has everything to do with entities. The fact that in this example the entity is physical has no bearing on it whatsoever. Nobody said anything about limiting OOP entities to physical entities. Right, sorry for going off on a tangent, it was 3am. :] When you're talking about something as simple as a customer it's true that an OOP approach probably doesn't add much to the equation. However, when you're dealing with complex entities which span several tables and have data stored in a different format to how it's used (think serialize) it makes sense to have a single point where you can get that data so that you don't end up duplicating the code needed to extract and store it. I'll have most of that handled by the database through triggers, updatable views, foreign keys etc. If this is not what you think OOP is all about, do please enlighten us as to the error of our ways. Imagine deleting many rows in a table one by one (pseudocode): snip instead of taking them with a single DELETE: snip Whoa nellie!! This is a question of design, not a question of whether to use OOP. Sure. I think obvious is the key word in Richard's statement: This is a classic example of the obvious OOP solution being wildly inappropriate. AFAICS he says that the obvious solution is wrong, not that OOP is wrong here. -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Roman Neuhauser [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] # [EMAIL PROTECTED] / 2006-10-11 21:28:36 +0100: Richard Lynch wrote: On Tue, October 10, 2006 6:14 pm, Chris de Vidal wrote: I want to create a customer class which fetches its attributes from a MySQL database. No, you don't. :-) This is a classic example of the obvious OOP solution being wildly inappropriate. Ok, so I now find myself in the unusual position of disagreeing with the Lynchmeister. Why is this wildly inappropriate? IMHO this is what OOP is all about. I have to disagree as well. There is absolutely nothing wrong which the approach of creating one class for each table in the database. It cannot be wrong for the simple reason THAT IT WORKS! It is also the simplest approach as it keeps all the business rules for each database entity in a single class. Also, by keeping the structure of each object in sync with the structure of the database you don't have to introduce another pointless level of complexity with OR mappers. Those OO purists who insist on creating object hierarchies which bear no resemblance to the database structure are making a rod for their own backs. That notion of purity is my idea of putrefaction. -- Tony Marston http://www.tonymarston.net http://www.radicore.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
By the way, about myself. I'm primarily a system administrator. Most of the time I USE code, NOT write it. But I also dabble, and right now we need to improve our old custom PHP revenue application which has sat stagnant for a few years. We can't afford a full-time programmer and I know enough to be dangerous ;-) So I'm the guy. All that to say I'm no pro and am humbly asking your collective professional opinions. --- Richard Lynch [EMAIL PROTECTED] wrote: I want to create a customer class which fetches its attributes from a MySQL database. No, you don't. :-) This is a classic example of the obvious OOP solution being wildly inappropriate. I'll consider that possibility. Start thinking more in terms of what you want the whole application to do, and build classes that do THAT, rather then starting with a single customer and their info. It seems you are advocating procedural programming here. I don't see how your use of classes are anything more than glorified functions. I could re-word the sentence above thusly: Start thinking more in terms of what you want the whole application to do, and build [functions] that do THAT... That's the path we went down at first and the net result was data access functions being copied and modified all over the place, making maintenance a real chore. Did it have speed? Yes. Do I hesitate to make changes to it? Yes. In a world where I am forced to choose between speed and maintainability, I'll probably choose speed, particularly when the program will be used daily. However, I truly believe a speedier OOD is attainable, which is why I'm asking. If, however, you are talking about some blending, where I create a procedural-style class and then make any modifications in subclasses which override the parent class, like this: class parentFunction { getRevenueForCustomer ($id) { // SELECT * FROM customer_revenue WHERE customer_id = '$id' } } class childFunction inherits parentFunction { // Overriding the parent function getRevenueForCustomer ($id, $year, $month, $department) { // SELECT * FROM customer_revenue WHERE customer_id = '$id' AND year = '$year' AND month = '$month' AND department = '$department' } } If that's what you mean, I honestly can't see how that saves coding time or helps maintenance, unless I need to also use some extraneous code with every query which would be included into the constructor. But then I could also use a function (instead of a class) which is like a query wrapper: function sql_query ($query) { // Some massaging routines // ... // Some more // ... $result = mysql_query ($query); // Error handling routines // ... // Other routines // ... return $result; } sql_query (SELECT * FROM ...); If that's the case, I don't see the need for classes at all, and that's actually the path we went down at first. We created a query function which massaged the input and handled errors. I've since learned that's not what I really wanted to do; I want to handle errors elsewhere. I think the above is easier to understand than using a class. Anyway, tell me what you have in mind. CD Think you#39;re a good person? Yeah, right! ;-) Prove it and get ten thousand dollars: TenThousandDollarOffer.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
On Wed, October 11, 2006 3:28 pm, Stut wrote: Richard Lynch wrote: On Tue, October 10, 2006 6:14 pm, Chris de Vidal wrote: I want to create a customer class which fetches its attributes from a MySQL database. No, you don't. :-) This is a classic example of the obvious OOP solution being wildly inappropriate. Ok, so I now find myself in the unusual position of disagreeing with the Lynchmeister. Why is this wildly inappropriate? IMHO this is what OOP is all about. You can encapsulate everything to do with a customer in an object. This ensures that you don't duplicate any code that works on customer data. You avoid duplication of code. As a result you can ensure data integrity because there is only one route to read and write it. If this is not what you think OOP is all about, do please enlighten us as to the error of our ways. Doing this without some kind of cache or some kind of bulk load of multiple customer data is inevitably going to lead to having a zillion customer instances floating around in one script to calculate something not readily expressed in an SQL aggregate. See other thread regarding 100 orders with all related uploaded files for an example. It's not so much that having a customer object is wrong, as that having ONLY a customer object to deal with an application that deals with MUCH MORE than a single customer at a time is wrong. You're going to end up having a TON of duplicate code for a single customer and multiple customers, or you're going to swamp your machine with way too many instances of a do-nothing object for the sake of being OOP And, in point of fact, unless you spend the majority of your time/energy in your application dealing with one customer at a time, it's quite likely that your one customer at a time can be encapsulated in a much more re-usable generalized notion of a set of customers -- albeit a set with only one element, and with a few specialized functions for certain operations with only work for one-element sets. Objectifying customer is the immediate, obvious, and totally inappropriate solution to needing to deal with not just one customer, but with sets of customers, some of which may, or may not, need special handling for a set with one element. This is merely the most obvious example of what is *probably* the needs of the original poster. One problem with OOP is that you really do need to understand very very very well the full scale and scope of your application before you can architect the appropriate OOP model. Its entirely possible that he does not need sets of customers, but needs some OTHER OOP model -- And there's no way to know without knowing the full scope of the project. You can do a bunch of simple object stuff in an iterative design, scale, scope interaction for rapid prototyping, but you have to be prepared to scrap all that code once you figure out what you REALLY wanted to do for your application, and you build the REAL application with the correct OOP model. Some Free Advice for a beginning OOP scripter. #1. Play around a lot with OOP on some non-mission-critical toy projects to get the feel of it. Build the smallest silliest OOP thing you can think of, and push the limits of class inheritence and how the pieces can be fit together in unusual ways. #2. Don't use a 'class' in a real project until you find yourself typing code that does almost the same thing as code you typed before, only it's just enough different to make an include or function unwieldy. At that juncture in time, figure out how you could relate the code you are typing NOW to the old code, and what common components you can abstract out to a base class and which parts are specializations of the base class. Re-code both chunks of code as OOP. *THAT* is the real power of OOP. Don't get me wrong: There are some other other uses of OOP, such as a substitute for namespaces for code for public release. But the obvious one-to-one mapping of real-world things to OOP classes seldom works out very well, unless your whole application is all about exploring/defining the relationships among those objects, rather than doing something complex with those objects. I *still* don't see OOP as a Right Answer for spitting out HTML web pages in optimized minimalist time frames... Maybe my brain just got warped by all that AI/Lisp work I did for a couple decades, but it feels to me like a bad selection of weapons for the task at hand, most times I see it in PHP. [shrug] -- Some people have a gift link here. Know what I want? I want you to buy a CD from some starving artist. http://cdbaby.com/browse/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
On Thu, October 12, 2006 12:49 am, Stut wrote: Roman Neuhauser wrote: # [EMAIL PROTECTED] / 2006-10-11 21:28:36 +0100: Richard Lynch wrote: On Tue, October 10, 2006 6:14 pm, Chris de Vidal wrote: I want to create a customer class which fetches its attributes from a MySQL database. No, you don't. :-) This is a classic example of the obvious OOP solution being wildly inappropriate. Ok, so I now find myself in the unusual position of disagreeing with the Lynchmeister. Why is this wildly inappropriate? IMHO this is what OOP is all about. To clarify my original statement. The *OBVIOUS* OOP setup of customer === class customer was the wildly in appropriate bit, not using OOP in some more sensible manner, like: //a set of customers class customers ( var customer_ids array(); } I believe my original post went on to say that more explicitly, but I can now see that many thought I was just railing against OOP in general, which was not my intent. (In *this* particular sentence, anyway. :-)) -- Some people have a gift link here. Know what I want? I want you to buy a CD from some starving artist. http://cdbaby.com/browse/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
On Thu, October 12, 2006 3:11 am, Tony Marston wrote: I have to disagree as well. There is absolutely nothing wrong which the approach of creating one class for each table in the database. It cannot be wrong for the simple reason THAT IT WORKS! Only problem is that then you often end up making ONE INSTANCE for each *row* in a large result set, and then you are in BIG TROUBLE. IT DOES NOT WORK! You've *got* to have some kind of other class that handles more than a couple handsful of the data, for anything other than a trivial application. And if it was trivial to start with OOP is rarely the right answer. -- Some people have a gift link here. Know what I want? I want you to buy a CD from some starving artist. http://cdbaby.com/browse/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
On Thu, October 12, 2006 8:24 am, Chris de Vidal wrote: [use the archives] I can't architect a good OOP solution to a problem that hasn't been fully defined, any more than one can architect a house without knowing all the rooms that are needed... I agree that all the code samples you provided below are wrong, if that helps. :-) If getRevenueForCustomer is all you need, then I'd have optional args for year and other factors, and have just one query and one function, and it does the right thing for that one customer. I'm assuming you need a heck of a lot more than that, though, so the above paragraph is not particularly helpful. The problem with an OOP discussion like this is that you have to have a complete understanding of what needs to be done before you can make sensible statement about what do do. It's POSSIBLE that class customer is the right answer, though I doubt it based on your original post about performance problems from having too many instances floating around. Maybe others' analysis that class customer was right, but not having the database access optimized with cache or with aggregators or something was the true problem. Maybe I even have a point about using class customers and operating on sets, even if it means specializing on the one-element-set. There's no way anybody can say for sure, not knowing the full scope of the application, though. -- Some people have a gift link here. Know what I want? I want you to buy a CD from some starving artist. http://cdbaby.com/browse/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
On Oct 12, 2006, at 10:18 AM, Richard Lynch wrote: I can't architect a good OOP solution to a problem that hasn't been fully defined, any more than one can architect a house without knowing all the rooms that are needed... Sorry to jump into the middle of the conversation, but I thought this was a pretty interesting comment. It serves as one of those occasional reminders that I need to go back and study OOP structure design a bit more. I know you're right about the importance of a fully defined problem, but it also seems that the reverse is true if you're really good with OOP. In other words, it seems like any high quality solution starts by defining least common denominators. You start with basic building blocks and expand from there; I'm always amazed when I see space stations or other complex structures built out of Legos, for example. My problem is that I usually look at OOP and think it'll take too long, so I go the non-OOP route, solve the problem, and move on. I can't help but think I'm missing out. I do have libraries of code that I reuse, but I've always heard that I'd benefit a lot more from them if I OOPed them. Dunno... that's my two cents worth anyway hehe -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Richard Lynch wrote: I *still* don't see OOP as a Right Answer for spitting out HTML web pages in optimized minimalist time frames... Maybe my brain just got warped by all that AI/Lisp work I did for a couple decades, but it feels to me like a bad selection of weapons for the task at hand, most times I see it in PHP. [shrug] There are different levels of applications that are 'spitting out HTML web pages'. If you're developing a system where each script is independent and simply makes use of shared code then OOP is almost certainly not worth it. When you get to a system of the size I deal with (several thousand files with several hundred classes and a single entry point) it becomes a lot easier to deal with that in an OOP fashion. As for your other posts about have a class that represents a single customer not being a good idea if you are going to be dealing with potentially large sets of customers, I would have to agree whole-heartedly. And I apologise if I read your post as an absolutely anti-OOP opinion when it was not. I came from a C/C++ background and feel that I understand the good and the bad effects of using OOP very well. In a PHP environment you generally need to take more care with how you architect the system to take into account the build and tear-down that occurs with each request, but OOP can still be used to great effect in large PHP sites. I do take issue with your 'free advice' when you say you should base your OOP code on your existing code. One of the things OOP does is allow/force you to think about the way you deal with data in your application from a different angle. That's definitely worth doing. In my experience developers get stuck in their habits far too easily and anything that causes you to re-evaluate the way you to things has to be worthwhile. Anyways, some of that probably didn't make much sense, so I need to write some code now. -Stut -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Ed Lazor wrote: On Oct 12, 2006, at 10:18 AM, Richard Lynch wrote: I can't architect a good OOP solution to a problem that hasn't been fully defined, any more than one can architect a house without knowing all the rooms that are needed... Sorry to jump into the middle of the conversation, but I thought this was a pretty interesting comment. It serves as one of those occasional reminders that I need to go back and study OOP structure design a bit more. I know you're right about the importance of a fully defined problem, but it also seems that the reverse is true if you're really good with OOP. In other words, it seems like any high quality solution starts by defining least common denominators. You start with basic building blocks and expand from there; I'm always amazed when I see space stations or other complex structures built out of Legos, for example. My problem is that I usually look at OOP and think it'll take too long, so I go the non-OOP route, solve the problem, and move on. I can't help but think I'm missing out. I do have libraries of code that I reuse, but I've always heard that I'd benefit a lot more from them if I OOPed them. Dunno... that's my two cents worth anyway hehe Except that is the attitude that leads to painful OOP in PHP. PHP is not the same environment as C++. The environment (classes, objects, etc) needs to be created and destroyed with each request. As such you cannot start designing a solution unless you know how the data/entities are going to be used. OOP in PHP cannot start with basic building blocks, at least not if you want a system that performs reasonably well. -Stut -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
On Thu, October 12, 2006 1:03 pm, Ed Lazor wrote: On Oct 12, 2006, at 10:18 AM, Richard Lynch wrote: I can't architect a good OOP solution to a problem that hasn't been fully defined, any more than one can architect a house without knowing all the rooms that are needed... Sorry to jump into the middle of the conversation, but I thought this was a pretty interesting comment. It serves as one of those occasional reminders that I need to go back and study OOP structure design a bit more. I know you're right about the importance of a fully defined problem, but it also seems that the reverse is true if you're really good with OOP. In other words, it seems like any high quality solution starts by defining least common denominators. You start with basic building blocks and expand from there; I'm always amazed when I see space stations or other complex structures built out of Legos, for example. My problem is that I usually look at OOP and think it'll take too long, so I go the non-OOP route, solve the problem, and move on. I can't help but think I'm missing out. I do have libraries of code that I reuse, but I've always heard that I'd benefit a lot more from them if I OOPed them. Dunno... that's my two cents worth anyway hehe Rapid prototyping in OOP, if you're willing to chuck the prototyping if it turns out to be the wrong OOP model is do-able. Even building the basic blocks first is fine -- but you've got to have the whole structure in your mind if you expect those blocks to fit in well. This is probably not really specific to OOP, but I think it tends to be more obvious with OOP when you start trying to work around the short-sighted architecture. By which I only mean that in procedural programming, the work-arounds feel less like work-arounds, at least at first, as they are not so obviously work-arounds, and just look like more functions. To get back to the ORIGINAL point -- OOP is not about raw performance. It's about maintainability, code re-use, encapsulation, etc. You can get acceptable performance from OOP if you know what you are doing -- If you don't, it's super easy for a beginner to write a total performance hog following all the best practices in the world. -- Some people have a gift link here. Know what I want? I want you to buy a CD from some starving artist. http://cdbaby.com/browse/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
# [EMAIL PROTECTED] / 2006-10-12 16:29:09 -0500: On Thu, October 12, 2006 1:03 pm, Ed Lazor wrote: On Oct 12, 2006, at 10:18 AM, Richard Lynch wrote: I can't architect a good OOP solution to a problem that hasn't been fully defined, any more than one can architect a house without knowing all the rooms that are needed... Sorry to jump into the middle of the conversation, but I thought this was a pretty interesting comment. It serves as one of those occasional reminders that I need to go back and study OOP structure design a bit more. I know you're right about the importance of a fully defined problem, but it also seems that the reverse is true if you're really good with OOP. In other words, it seems like any high quality solution starts by defining least common denominators. You start with basic building blocks and expand from there; I'm always amazed when I see space stations or other complex structures built out of Legos, for example. My problem is that I usually look at OOP and think it'll take too long, so I go the non-OOP route, solve the problem, and move on. I can't help but think I'm missing out. I do have libraries of code that I reuse, but I've always heard that I'd benefit a lot more from them if I OOPed them. Dunno... that's my two cents worth anyway hehe Rapid prototyping in OOP, if you're willing to chuck the prototyping if it turns out to be the wrong OOP model is do-able. Even building the basic blocks first is fine -- but you've got to have the whole structure in your mind if you expect those blocks to fit in well. Erm, I stopped doing BDUFs when I had to throw out two unimplementable designs and 2 x approx. 2000 LOC. The third attempt grew test-first, with better results. -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Comments / Questions below. On Oct 12, 2006, at 12:15 PM, Stut wrote: Except that is the attitude that leads to painful OOP in PHP. PHP is not the same environment as C++. The environment (classes, objects, etc) needs to be created and destroyed with each request. I definitely agree that PHP is not the same as C++. I agree with the need for high efficiency and performance with low overhead. Actually, it's funny you mention that, because I've argued those same points with C/C++ coders new to PHP. As such you cannot start designing a solution unless you know how the data/entities are going to be used. Doesn't this mean that your design breaks when the behavior or use of the data/entities changes? OOP in PHP cannot start with basic building blocks, at least not if you want a system that performs reasonably well. Right. That makes sense with PHP being an interpreted language. I've tried to offset this somewhat by compiling libraries and having them cached before pages that rely on these libraries load. I'm trying to get a better idea of how you leverage the advantage of OOP in PHP. Do you use it? If so, how? Do you use any OOP methodologies? If so, which ones? For that matter, how many of your projects start with a detailed description of all data/entities and how they are going to be used? Does your experience differ a lot from mine? My customers rarely have a complete understanding of what they'll be doing. They usually only have a general idea. Part of my challenge is to help them define that idea, especially when it comes to defining the scope of the initial project. Yes, scope creep is to be avoided or managed in projects, but customers are always finding new and creative ways to apply their ideas. Things have to be flexible enough to support current needs and future needs. You're saying that you cannot start designing a solution unless you know how the data/entities are going to be used. I'm saying that you have to start somewhere and that code has to be extensible enough to meet growing demands. I'm sure that you try to come up with flexible designs, but I'm wondering. What is your approach? Also, isn't OOP supposed to be about separating data from programming logic? If that's the case, isn't how you use that data irrelevant? That seems like one of the greatest promises of OOP, but maybe that's just the hype? On Oct 12, 2006, at 2:29 PM, Richard Lynch wrote: Rapid prototyping in OOP, if you're willing to chuck the prototyping if it turns out to be the wrong OOP model is do-able. Do you end up throwing away a lot of code? Even building the basic blocks first is fine -- but you've got to have the whole structure in your mind if you expect those blocks to fit in well. It sounds like you (Both Stut and Richard) have done a lot of this, so I'm sure you know what you're talking about. Like I mentioned in my original post, I think I need to spend time learning better object modeling in order to take better advantage of OOP. I still can't help but wonder. How do you know if you have the full structure? Don't you end up going back and changing things a lot? This is probably not really specific to OOP, but I think it tends to be more obvious with OOP when you start trying to work around the short-sighted architecture. By which I only mean that in procedural programming, the work-arounds feel less like work-arounds, at least at first, as they are not so obviously work-arounds, and just look like more functions. I'm honestly not sure if I understand what you're saying here, but I do know that I've always tended more toward linear / procedural programming with a lot of functions. I have used OOP, but in very limited capacity - mainly to avoid the system overhead. I think I've also avoided it because I usually run into problems with defining data in objects - similar to the original issue of creating a customer object only to run into the problem of how to handle objects that represent a collection of customers. Again, me needing to get a better understanding of data modeling in OOP. It seems like you still end up having to learn data modeling the PHP way; people are probably critical of PHP because of this, but it seems like there's a middle ground and I'm curious where you guys have found that to be. Should I take this off the mailing list and talk with you about it in separate email? To get back to the ORIGINAL point -- OOP is not about raw performance. It's about maintainability, code re-use, encapsulation, etc. You can get acceptable performance from OOP if you know what you are doing -- If you don't, it's super easy for a beginner to write a total performance hog following all the best practices in the world. Definitely agree with you there. -Ed -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Richard Lynch [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] On Thu, October 12, 2006 3:11 am, Tony Marston wrote: I have to disagree as well. There is absolutely nothing wrong which the approach of creating one class for each table in the database. It cannot be wrong for the simple reason THAT IT WORKS! Only problem is that then you often end up making ONE INSTANCE for each *row* in a large result set, and then you are in BIG TROUBLE. IT DOES NOT WORK! You've *got* to have some kind of other class that handles more than a couple handsful of the data, for anything other than a trivial application. I don't have, and never will have, one instance for each row. One instance can deal with any number of rows. And if it was trivial to start with OOP is rarely the right answer. Something may start as trivial, but over time it can expand into something more than trivial, by which time you will lose out by not going down the OO route to begin with. -- Tony Marston http://www.tonymarston.net http://www.radicore.org -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Ed Lazor wrote: On Oct 12, 2006, at 12:15 PM, Stut wrote: As such you cannot start designing a solution unless you know how the data/entities are going to be used. Doesn't this mean that your design breaks when the behavior or use of the data/entities changes? You may end up refactoring code if your application changes that much, but a good OO design should also mean that when changes of that magnitude occur the changes required are limited to relatively small sections of code. OOP in PHP cannot start with basic building blocks, at least not if you want a system that performs reasonably well. Right. That makes sense with PHP being an interpreted language. I've tried to offset this somewhat by compiling libraries and having them cached before pages that rely on these libraries load. I'm trying to get a better idea of how you leverage the advantage of OOP in PHP. Do you use it? If so, how? Do you use any OOP methodologies? If so, which ones? For that matter, how many of your projects start with a detailed description of all data/entities and how they are going to be used? My general approach to designing a system is data-centric. I tend to start by defining the database schema since getting that clear in my head tends to lead me to a decent design. For most projects I don't start out with OOP in mind, but my brain is used to building OOP-style systems so nearly everything I do ends up with a few classes. For example, I'm currently working on a site for a couple of friends of mine. The site has an extremely simple user system - hard-coded passwords (evil I know, but it's what they asked for). When I first came to authenticate the user I naturally created a User class with three static methods: Login, Logout and IsLoggedIn. The class stores the logged in status and access level in the session. When I actually get to implementing something that requires a logged in user I will create another static method called Can which will tell me if a user can do a particular thing. Off the top of my head, that Can method will look something like... static public function Can($action) { if (!self::IsLoggedIn()) return false; return (in_array($action, $_SESSION['user']['perms'])); } For this simple example everything is hard-coded and all data required is stored in that class, including the passwords and actions allowed by each access level. Now consider that a couple of months down the line they decide they want to implement a complete DB-based user system, all I do is modify the User class to add the methods that would need incorporating getting users from the database. I can do this because I know that each visitor will only be accessing one user at a time so the performance hit is negligible. If I then go on to create an admin interface for the users, I would create another completely separate class called UserCollection to handle more than one user. I may at that point choose to expose any data-massaging methods in User to UserCollection to avoid code duplication, but that would be the extent of the way UserCollection uses the User class since the User class is optimised to work on a single user at any one time. Does your experience differ a lot from mine? My customers rarely have a complete understanding of what they'll be doing. They usually only have a general idea. Part of my challenge is to help them define that idea, especially when it comes to defining the scope of the initial project. Yes, scope creep is to be avoided or managed in projects, but customers are always finding new and creative ways to apply their ideas. Things have to be flexible enough to support current needs and future needs. You're saying that you cannot start designing a solution unless you know how the data/entities are going to be used. I'm saying that you have to start somewhere and that code has to be extensible enough to meet growing demands. I'm sure that you try to come up with flexible designs, but I'm wondering. What is your approach? To me it's all about numbers. I think the worst way you can apply OOP in PHP is by-the-book. What you need to do is look at defining your entities in relation to their existance within each request. Taking my user example above, I know that for the bulk of the system only one user will ever be needed. This makes it perfect for an object-per-record implementation since there is only one record. When I discuss a system with a customer my head is taking what they are saying and mapping it into several entities, not all of which will become actual classes, but all of which help me organise the site before doing any coding. Examples of these entites would be sections of the site, individual pages, data sets, access limits, etc. and the way those will interact with each other to provide a solution. All requirements change - fact of life. Customers never know what they really want. OOP
Re: [PHP] OOP slow -- am I an idiot?
On Oct 12, 2006, at 4:36 PM, Stut wrote: You may end up refactoring code if your application changes that much, but a good OO design should also mean that when changes of that magnitude occur the changes required are limited to relatively small sections of code. Ok, I think we're using the same approach here. I also noted the earlier comments about BUDF and I'm exploring those. It would be nice if anyone else has more examples of standard methodologies applied to PHP. My general approach to designing a system is data-centric. I tend to start by defining the database schema since getting that clear in my head tends to lead me to a decent design. Same here, most of the time. There are a few situations where I focus more on just giving the customer canned solutions and finding ways to integrate them as easily as possible. This is usually when the customer wants all kinds of features, but they can't really afford them. For example, one guy approached me the other day asking me to code forums, a community calendar, news, a rant section, a products database with inventory management, a shopping cart system, and coming up with a layout and design that integrates it all... then he said... he needs it in two weeks, it has to be priced under $400, and he needs to be able to easily update content on his own. ugh. I told him flat out that his price was way off and that he'd best go with pre-made solutions like PHPBB to get what he's after. If I then go on to create an admin interface for the users, I would create another completely separate class called UserCollection to handle more than one user. I may at that point choose to expose any data-massaging methods in User to UserCollection to avoid code duplication, but that would be the extent of the way UserCollection uses the User class since the User class is optimised to work on a single user at any one time. We use a similar approach for the user class. I haven't ever implemented something like the UserCollection class though. I'm curious about that. Does your UserCollection class extend the basic user class? Or is it something else entirely; I dunno, maybe UserCollection has a property defined as an array of User class? I think that's what people were saying earlier in the thread as being a very bad thing in terms of memory utilization, etc. How to properly define the User class and UserCollection classes also seems to delve into issues of UML and CORBA, which I don't have a lot of experience with. Is anyone applying those technologies to PHP? This makes it perfect for an object-per-record implementation since there is only one record. Yea, but I keep thinking back to how the implementation of data representation is separate from the implementation of how that data is used. Going back to the users example, I created a User class. I never bothered to create a UserCollection class because coding that does anything with a collection of users typically ends up being situational. Say I want a list of customers. I could create a UserCollection class with a method called list... and I could have it query the db and dump general fields. That seems like a fairly generic approach, so it might work, but I usually want to do something with individual fields - like link to a specific webpage to view more information on the customer, edit the customer record, delete, etc.. I know I could code all of these features into the class... but it reaches the point where it seems like overkill. It seems better to just create a webpage that has code to handle that which is what I end up doing. Mind you, I once created a bunch of classes that did all of the cool pretty formatting, table layout, with customizable doohikies, but that's where the classes started getting bloated, the system started bogging down, and there were very small, but very noticeable, delays in loading pages. I guess that leads me back to wondering how you implemented the UserCollection class or, at least, what features you built into it in order for it to be of benefit. I'm also assuming (uhoh hehe) that the same thing applies to other object hierarchies - for example, one class that defines a product and another class that defines a collection of products wondering how the two would be implemented to maintain efficiency... and I'm guessing your answer is that how you implement it depends on the situation... whether the site focuses on using individual products the most or ends up working with collections of products most... but it seems like it wouldn't matter... ie. again, the separation of data from implementation. All requirements change - fact of life. Customers never know what they really want. OOP will not shield you from the effects of having the system specification pulled from under your feet. However, it can be used to
Re: [PHP] OOP slow -- am I an idiot?
--- Johan Martin [EMAIL PROTECTED] wrote: You should look into getting Professional PHP5 by Lecky-Thompson, Eide-Goodman, Nowicki and Cove from WROX. ... The collection class in chapter 5 discusses a programming problem just like yours. I will look into that, thank you. CD Think you#39;re a good person? Yeah, right! ;-) Prove it and get ten thousand dollars: TenThousandDollarOffer.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
--- Larry Garfield [EMAIL PROTECTED] wrote: For your rudimentary example of object-relational mapping below, yes, performance is going to be atrocious. That's because you're not taking any advantage of the features that using OOP gives you. Well, I /thought/ I was taking advantage of black box-style hiding (not sure what it's called), that is, making sure the only place I type (and modify) my SQL query is hidden inside the private method of a class. Again, pull extra data if you can. A somewhat larger result set is (usually) better than multiple queries. How much you want to front-load in your object and how much you want to defer to later depends on your specific problem and how frequently the data will be used. OK that somewhat answers the question. 5) If you need to grab 100 objects at once, but just need basic data out of them, use a factory. Vis, (code snipped) I /think/ I understand the code. But I'd need more than just basic data, so I probably will just write a query. 6) If you need to do a complex query with a couple of joins and such, then don't waste your time or the computer's trying to shoe-horn it into SQL. SQL is not inherently OO to start with! Just write your query and loop it and be happy. OOP is not the answer to all problems. Sometimes it does just make matters worse, no matter what Sun tries to tell you. :-) LOL Yeah, I was thinking of shoe-horning things into SQL for speed. I want my data to _only_ be accessed from the black box called an OOP class. That will work and is achievable in about 30% of all situations. For the other 70%, you will have to just hunker down and *gasp* write SQL specific to the task at hand at least some of the time. How much of the time once again depends on your situation and the problem you're trying to solve. *gasp* :-) From what it seems like people are telling me, it's a good idea to boot OOP for large numbers of objects where I need more than just a little information and just use an SQL query, as I suspected. At least, for PHP; I wonder what Java people do in this situation. CD Think you#39;re a good person? Yeah, right! ;-) Prove it and get ten thousand dollars: TenThousandDollarOffer.com -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
- Original Message - From: Chris de Vidal [EMAIL PROTECTED] To: php-general@lists.php.net Sent: Wednesday, October 11, 2006 12:42 PM Subject: Re: [PHP] OOP slow -- am I an idiot? --- Johan Martin [EMAIL PROTECTED] wrote: You should look into getting Professional PHP5 by Lecky-Thompson, Eide-Goodman, Nowicki and Cove from WROX. ... The collection class in chapter 5 discusses a programming problem just like yours. I will look into that, thank you. CD Regardless of whether you find the sugested book or not, do take note that a good place for functions as the one you require, as Johan sugestests, isin a class representing collections of the individual objects. Thus, it is usually good to have a class representing individual objects (customer) and collections of the same (customers) or methods that provide information on groups or agregates of individual items. Satyam -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
On Tue, October 10, 2006 6:14 pm, Chris de Vidal wrote: I want to create a customer class which fetches its attributes from a MySQL database. No, you don't. :-) This is a classic example of the obvious OOP solution being wildly inappropriate. The sad thing is, there are a zillion applications out there doing it just this way... :-( Start thinking more in terms of what you want the whole application to do, and build classes that do THAT, rather then starting with a single customer and their info. -- Some people have a gift link here. Know what I want? I want you to buy a CD from some starving artist. http://cdbaby.com/browse/from/lynch Yeah, I get a buck. So? -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Richard Lynch wrote: On Tue, October 10, 2006 6:14 pm, Chris de Vidal wrote: I want to create a customer class which fetches its attributes from a MySQL database. No, you don't. :-) This is a classic example of the obvious OOP solution being wildly inappropriate. Ok, so I now find myself in the unusual position of disagreeing with the Lynchmeister. Why is this wildly inappropriate? IMHO this is what OOP is all about. You can encapsulate everything to do with a customer in an object. This ensures that you don't duplicate any code that works on customer data. You avoid duplication of code. As a result you can ensure data integrity because there is only one route to read and write it. If this is not what you think OOP is all about, do please enlighten us as to the error of our ways. -Stut -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
# [EMAIL PROTECTED] / 2006-10-11 21:28:36 +0100: Richard Lynch wrote: On Tue, October 10, 2006 6:14 pm, Chris de Vidal wrote: I want to create a customer class which fetches its attributes from a MySQL database. No, you don't. :-) This is a classic example of the obvious OOP solution being wildly inappropriate. Ok, so I now find myself in the unusual position of disagreeing with the Lynchmeister. Why is this wildly inappropriate? IMHO this is what OOP is all about. No, that's what trivial OOP examples applied to the letter where a different approach is in order are. If you study the GoF book [GoF] you'll see that the traditional claim objects model physical entities from real world (and nothing else) is very simplistic and terribly limiting. [GoF] http://www.amazon.com/dp/0201633612/ If you paint yourself into this corner you'll find your code grinding the database to death in the OO-relational impedance mismatch. The OOP ideal of a single source of data is nice, unfortunately the real world gets in the way. You can encapsulate everything to do with a customer in an object. This ensures that you don't duplicate any code that works on customer data. You avoid duplication of code. As a result you can ensure data integrity because there is only one route to read and write it. Who talks about duplicating business logic? You just need to have more than one access point for the data. If this is not what you think OOP is all about, do please enlighten us as to the error of our ways. Imagine deleting many rows in a table one by one (pseudocode): class Record { function __construct($id) { $this-id = $id; } function delete() { // DELETE FROM some_table WHERE id = $this-id } } foreach ($records as $r) { $r-delete(); } instead of taking them with a single DELETE: // assuming // class Search; // $searchBuilder = new SearchBuilder; // $SearchBuilder-add(new LessThan('id', '501')); // $search = $searchBuilder-result(); class RecordSet { function __construct(Search $search) { $this-search = $search; } function delete() { // DELETE FROM some_table WHERE $this-search-toSQL() } } $recordset($search); $recordset-delete(); -- How many Vietnam vets does it take to screw in a light bulb? You don't know, man. You don't KNOW. Cause you weren't THERE. http://bash.org/?255991 -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Roman Neuhauser wrote: # [EMAIL PROTECTED] / 2006-10-11 21:28:36 +0100: Richard Lynch wrote: On Tue, October 10, 2006 6:14 pm, Chris de Vidal wrote: I want to create a customer class which fetches its attributes from a MySQL database. No, you don't. :-) This is a classic example of the obvious OOP solution being wildly inappropriate. Ok, so I now find myself in the unusual position of disagreeing with the Lynchmeister. Why is this wildly inappropriate? IMHO this is what OOP is all about. No, that's what trivial OOP examples applied to the letter where a different approach is in order are. If you study the GoF book [GoF] you'll see that the traditional claim objects model physical entities from real world (and nothing else) is very simplistic and terribly limiting. [GoF] http://www.amazon.com/dp/0201633612/ If you paint yourself into this corner you'll find your code grinding the database to death in the OO-relational impedance mismatch. The OOP ideal of a single source of data is nice, unfortunately the real world gets in the way. I never said anything about physical entities. The OOP methodology has nothing to do with physical entities, but it has everything to do with entities. The fact that in this example the entity is physical has no bearing on it whatsoever. Nobody said anything about limiting OOP entities to physical entities. You can encapsulate everything to do with a customer in an object. This ensures that you don't duplicate any code that works on customer data. You avoid duplication of code. As a result you can ensure data integrity because there is only one route to read and write it. Who talks about duplicating business logic? You just need to have more than one access point for the data. If you have more than one access point for the data you end up with a more complicated maintenance situation since you may have several places that treat the data differently. This is bad m'kay. When you're talking about something as simple as a customer it's true that an OOP approach probably doesn't add much to the equation. However, when you're dealing with complex entities which span several tables and have data stored in a different format to how it's used (think serialize) it makes sense to have a single point where you can get that data so that you don't end up duplicating the code needed to extract and store it. If this is not what you think OOP is all about, do please enlighten us as to the error of our ways. Imagine deleting many rows in a table one by one (pseudocode): snip instead of taking them with a single DELETE: snip Whoa nellie!! This is a question of design, not a question of whether to use OOP. For example, in several of the sites I maintain I have classes that inherit from a base class called Table. The base class provides a lot of the basic methods for working on a table (think ActiveRecord). It also has static methods for doing things like updates and deletes based on a where clause. The derived classes can override filter methods (AfterLoad and BeforeSave) to massage the data after it's loaded and before it's saved. They also add any methods needed for acting on that particular entity. I'm the first to admit that OOP is not always the best methadology to use - the 'best methadology for all situations' does not exist. However, the general feeling people will get towards OOP from this list seems to be 'OOP bad, anything else better'. OOP is great as long as you follow OOD principles and have a fair amount of common sense. It should not be used just because it's there, but it should also not be dismissed. In fact, in writing that I've just realised that OOP is not the key... OOD is. OOD can be applied (with no syntax or compiler assistance) in a functional system which will have great benefits, all of which I think most people are aware of but, for whatever reason, fail to adequately apply - which is where OOP can be useful since it enforces the structure and protection through the syntax (PHP4 sucked for this, PHP5 is better). When you actually think about it, OOP is not a methadology - it's a syntax. OOD is the methadology. Ramble... ramble... ramble... over! -Stut -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
Chris de Vidal wrote: I think perhaps I'm using classes and OOP incorrectly. The last time I used them, they were slow. The examples you provided shows that it's not OOP that's the problem, it's how your getting the data as you suspected. Doing tons of queries is going to be slow whether you're using OOP or functional programming. Depending on your app, you could pass in arrays of data: getRevenue($customer_id, $departments=array(), $years_to_fetch=array()) { ... sanitize $departments and $years_to_fetch $query = SELECT revenue FROM customer_revenue WHERE customer_id = '$customer_id' AND department IN ( . $departments . ) AND year IN ( . $years_to_fetch . ); } Because php is loosely typed you can take advantage of that. Only want to pass in one department? Change it to be an array and go from there: if (!is_array($departments)) { $departments = array($departments); } Depends a lot on the situation as well. If it's for a report that's going to be run once a year, a few extra queries probably isn't going to make any difference. Something that gets called every time? Optimize it as much as possible. I've used both methods and they both have their merits. Context is important too :) If I need to create a queue of items to go through (eg the web interface creates a queue for a cron job to pick up and process), then I'll do everything straight in the database and nothing in PHP (well as much as possible anyway) by passing in everything I need and writing a query to handle it all. After all that, I probably didn't help much ;) -- Postgresql php tutorials http://www.designmagick.com/ -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP] OOP slow -- am I an idiot?
For your rudimentary example of object-relational mapping below, yes, performance is going to be atrocious. That's because you're not taking any advantage of the features that using OOP gives you. One could write a dissertation on this problem, but I will just give you some general guidelines. (All code examples below assume PHP 5.) 1) OOP has overhead. In most situations, if you can write something in a fully OOP fashion or a direct procedural fashion, the direct procedural will perform faster. How much faster depends on the situation and the experience level of the programmer. What OOP can get you is flexibility. There are cases where OOP code is faster than the corresponding procedural, but none of them involve SQL. :-) 2) Burn some memory on private variables. That's what they're there for. Eg: public class Foo { private $id=0; private $bar=0; private $baz=''; function __construct($id) { // Do your type checking and escaping here $result = mysql_query(SELECT * FROM Foo WHERE id={$id}); $record = mysql_fetch_object($result); $this-id = record-id; $this-bar = record-bar; $this-baz = record-baz; } function getBaz() { return $this-baz; } } You'll want to be a lot smarter than the code above to avoid drudge work in the code, but you get the idea. Front-load as much of the object's information has you can in the constructor, within reason. A good rule of thumb is that anything you can get in the initial query (like above) you should and then cache. That saves you putting wasteful SQL queries in your getters. 3) Data you have to load later from another table, delay until you need to get it but then cache that as well. function getRevenue ($id,$department,$month,$year) { if (!$this-revenue) { $result = mysql_query (SELECT revenue FROM customer_revenue WHERE customer_id = '$id' AND department = '$department' AND month = '$month' AND year = '$year'); $this-revenue = mysql_result ($result, 0); } return $this-revenue; } Again, pull extra data if you can. A somewhat larger result set is (usually) better than multiple queries. How much you want to front-load in your object and how much you want to defer to later depends on your specific problem and how frequently the data will be used. 4) You can optimize your SQL structure for easier object usage. Often that just means proper normalization, sometimes you'll want to denormalize in specific places to improve performance. Again, depends on your situation. 5) If you need to grab 100 objects at once, but just need basic data out of them, use a factory. Vis, $myobjects = Foo::getObjects(array(1, 2, 3)); class Foo { static function getObjects($ids) { $return = array(); $result = mysql_query(SELECT * FROM Foo WHERE id IN ( . implode(',', $ids) . )); while ($record = mysql_fetch_object($result)) { $foo = new Foo(); $foo-setProperties($record); $return[] = clone($foo); } return $return; } function setProperties($properties) { // Left as an exercise to the reader } } 6) If you need to do a complex query with a couple of joins and such, then don't waste your time or the computer's trying to shoe-horn it into SQL. SQL is not inherently OO to start with! Just write your query and loop it and be happy. OOP is not the answer to all problems. Sometimes it does just make matters worse, no matter what Sun tries to tell you. :-) I want my data to _only_ be accessed from the black box called an OOP class. That will work and is achievable in about 30% of all situations. For the other 70%, you will have to just hunker down and *gasp* write SQL specific to the task at hand at least some of the time. How much of the time once again depends on your situation and the problem you're trying to solve. On Tuesday 10 October 2006 18:14, Chris de Vidal wrote: I think perhaps I'm using classes and OOP incorrectly. The last time I used them, they were slow. I want to create a customer class which fetches its attributes from a MySQL database. Something like this pseudocode: class customer { ... getName ($id) { $result = mysql_query (SELECT name FROM customers WHERE id = '$id'); return mysql_result ($result, 0); } getRevenue ($id,$department,$month,$year) { $result = mysql_query (SELECT revenue FROM customer_revenue WHERE customer_id = '$id' AND department = '$department' AND month = '$month' AND year = '$year'); return mysql_result ($result, 0); } ... } (Again, that's just psedocode. Haven't written anything yet.) That works great for just one revenue result, but what if I want to return several results? What if I want to build a report with hundreds of customers' revenues for a month? For several months? For an entire year? Doesn't it slow wa down? It seemed to in the past. The method above
Re: [PHP] OOP slow -- am I an idiot?
On 10 Oct 2006, at 4:14 PM, Chris de Vidal wrote: I think perhaps I'm using classes and OOP incorrectly. The last time I used them, they were slow. I want to create a customer class which fetches its attributes from a MySQL database. Something like this pseudocode: class customer { ... getName ($id) { $result = mysql_query (SELECT name FROM customers WHERE id = '$id'); return mysql_result ($result, 0); } getRevenue ($id,$department,$month,$year) { $result = mysql_query (SELECT revenue FROM customer_revenue WHERE customer_id = '$id' AND department = '$department' AND month = '$month' AND year = '$year'); return mysql_result ($result, 0); } ... } You should look into getting Professional PHP5 by Lecky-Thompson, Eide-Goodman, Nowicki and Cove from WROX. It's a good introduction to using PHP5 with design patterns to solve problems similar to yours. Plus, the knowledge can be applied to other object oriented programming languages, not just PHP5. It's also been out for a while so it may be in the sale section already. The collection class in chapter 5 discusses a programming problem just like yours. Johan Martin Catenare LLC 534 Pacific Ave San Francisco, CA. 94133 http://www.catenare.com http://www.linkedin.com/in/catenare -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php