I think the main thing here is that you don't have to design everything first. You'll probably want an overall, high-level "map" describing your application's components, sub-systems, or whatever you want to call them.

Then you can drill down into whichever component you deem most important to work on first, and flesh out its design. At this point you may be defining classes, or you may need to drill down further, depending on the size and complexity of the app.

    I've heard from experienced engineers of all stripes that long before one finishes any engineering project that one has already thought of a better way to do it. So don't worry too much about trying to make it perfect before you start because you simply won't.

    On the other hand, putting a bit of thought into the overall design could save you a lot of trouble later. Personally, I find it enough of a chore to determine what classes I'll need. I usually spend a lot of time contemplating that. I always like to have classes to handle sessions and data access. I also find that it's important to have ONE FILE that you can modify to change the behavior of every single page on your site.

      sneakyimp;10922564 wrote:

      I've heard from experienced engineers of all stripes that long before one finishes any engineering project that one has already thought of a better way to do it. So don't worry too much about trying to make it perfect before you start because you simply won't.

      So true.

      On the other hand, putting a bit of thought into the overall design could save you a lot of trouble later. Personally, I find it enough of a chore to determine what classes I'll need. I usually spend a lot of time contemplating that. I always like to have classes to handle sessions and data access. I also find that it's important to have ONE FILE that you can modify to change the behavior of every single page on your site.

      Well, I picked up a book at Barnes & Noble yesterday - don't remember the title/author - and it got into all of this really deep and abstract stuff about how to model classes. And I think it may have gotten into multiple inheritance which at least we can avoid in PHP.

      I have a pretty extensive RDBMS background and used to be pretty deft at doing Database Modeling.

      With that said, I would normally start looking for "Entities" (e.g. Customer, Order, OrderItem, Product) to design my system. And this is where I get nervous...

      See, I always view the world in terms of "data" but I think you OOP guys abstract the world differently and I'm not sure where or how or why?! :queasy:

      What "paradigm" would you OOP guys/gals use to abstract an E-commerce??
      Would your classes model...

      • Data??

      • Business Logic??

      • Website Components??

      • Process (e.g. Use-Case) Flow??

      • Other??

      • Some combination of the above??

      There seems to be lots of ways to approach this, and they all diverge, so kind of like Dorthy in "The Wizard of Oz", one needs to either choose Left or Right?!

      See where I am coming from??

      Amy

        Given that you have database experience, I would recommend you create some DAO/DTO classes for your database tables so that creating, updating, and deleting records is easier. I always try to use an object to encapsulate my database access because you never know when you'll need to switch from MySQL running on a single machine to distributed MySQL running on a number of replicating machines because your site is now so popular. You need a point at which you can intercept all traffic to the database. There are an infinite number of ways you can go about this--miminally, just a single wrapper class with a method for each of the basic MySQL functions. Or, you could get more involved...there's a good thread here on that topic.

        As you design your database classes, you will probably be thinking of how you'll need to push data around in response to user activity on the site. In fact, your DB tables probably already anticipate certain actions like purchases, sales, etc. Once you've created your basic db wrapper stuff, you'll have some objects that can be used to push that data around. At that point, you might use those objects as building blocks to create higher-level, more abstract objects for things like 'Product'. You might want to write a method for product called "displayHTML" which, somewhat shockingly, might output an html rendering of the product's features.

        Or something like that. I'd just try to get some code to manipulate the database and then start thinking of objects to build that connect those to the HTML in such a way that people can see it. Somewhere along the way to doing that, you might consider ways to build display methods such that you can use templates or "skins" for your site -- like one for big-screen browsers and another for smart phone screens.

        Ultimately the classes you write should save you time coding OR if they are time-consuming to write then they should provide some serious benefit (like security or maintainability or something). The only way you'll know if they save you time is if you start coding with them.

          You should serve milk with responses like this?! :p

          sneakyimp;10922585 wrote:

          Given that you have database experience, I would recommend you create some DAO/DTO classes for your database tables so that creating, updating, and deleting records is easier.

          Ah, but I have NO OOP experience, so let me translate what you said... (My background is also more with the modeling part.)

          DAO =? Data Access Objects

          DTO =? Data Transformation Objects

          (DDL, DML, and DCL are more common acronyms from my former world.)

          I guess what you are saying is that I should use OOP to control how I interact with my database??

          I always try to use an object to encapsulate my database access because you never know when you'll need to switch from MySQL running on a single machine to distributed MySQL running on a number of replicating machines because your site is now so popular. You need a point at which you can intercept all traffic to the database. There are an infinite number of ways you can go about this--miminally, just a single wrapper class with a method for each of the basic MySQL functions. Or, you could get more involved...there's a good thread here on that topic.

          I'd have to see examples, but think I follow you at a higher level.

          Okay, so here you are suggesting modeling Database-Access Classes...

          As you design your database classes, you will probably be thinking of how you'll need to push data around in response to user activity on the site. In fact, your DB tables probably already anticipate certain actions like purchases, sales, etc. Once you've created your basic db wrapper stuff, you'll have some objects that can be used to push that data around. At that point, you might use those objects as building blocks to create higher-level, more abstract objects for things like 'Product'.

          And here you are suggesting modeling Data Classes...

          You might want to write a method for product called "displayHTML" which, somewhat shockingly, might output an html rendering of the product's features.

          Or something like that. I'd just try to get some code to manipulate the database and then start thinking of objects to build that connect those to the HTML in such a way that people can see it. Somewhere along the way to doing that, you might consider ways to build display methods such that you can use templates or "skins" for your site -- like one for big-screen browsers and another for smart phone screens.

          Okay, so those would be Website-Component Classes...

          Ultimately the classes you write should save you time coding OR if they are time-consuming to write then they should provide some serious benefit (like security or maintainability or something). The only way you'll know if they save you time is if you start coding with them.

          Good general advice!!

          But what about some of the other areas I mentioned? I would think these would be the "hot" areas to model...

          Business-Logic Classes??
          - Calculate Sales Tax
          - Estimate Delivery Date
          - Manage Inventory
          - Handle Refund
          - Recommend Products

          Website-Components Classes??
          - Browse Products
          - Search for Product
          - Manage User Profile/Preferences
          - Display Product Catalog
          - Navigate Site
          - Display Template

          Process-Flow Classes??
          - Register User
          - Authenticate User
          - Search for Product
          - Manage Shopping Cart
          - Checkout Process
          - Handle Credit Card Payment
          - E-mail Receipt
          - Handle RMA

          Other Classes??
          - Determine User Browser Type
          - Determine User Op Sys
          - Maintain Sessions/Persistence
          - Update Product Info/Availability

          Those are example of things I would think you might want to turn into Classes, but there are just so many ways to come at things?! :queasy::queasy:

          I realize there are OOP "Patterns", but those seem to focus at a much more granular level.

          Aren't there established "Patterns" at a higher level (e.g. "Business-Logic Patterns", "Process-Flow Patterns")?? (Because I assume you want to avoid having thousands of disconnected and discombobulated Classes?!)

          whew

          Okay, I'm done for now! 🙂

          Amy

            Try reading the other thread that I linked. Although I have a lot of experience, I don't really know the terminology you may have read about. I tend to write some basic classes and then go all procedural just to get things done. The bottom line is that I can write a class, but missed the lecture about the higher level concepts.

            And, for the record, I'd probably serve booze.

              "But my fear is that I have to do all this fancy, heavy-duty OOA/OOD and fill my apartment with hundreds of UML diagrams - and crazy theory - before I can start building any application?"

              That is more waterfall( Big Design Up Front http://en.wikipedia.org/wiki/Big_Design_Up_Front ) than OOP. It is not actually really indicative of OOP as a whole, it is a project management approach. Get everything in stone and agreed with a client before building and then the outcome has to match that spec exactly. Problem with that is the client can often get what they asked for not what they wanted( change becomes very hard and causes frictions, possibly legal as both sides see the document differently ).

              In iterative development emergent design is used( http://en.wikipedia.org/wiki/Iterative_and_incremental_development ).

              "
              Business-Logic Classes??
              - Calculate Sales Tax
              - Estimate Delivery Date
              - Manage Inventory
              - Handle Refund
              - Recommend Products
              "

              Yep you get the right idea... You could sit there today and write something that calculated sales tax with no other part of the site done as it has its own set of rules which have to be adhered to( the goverment makes it up ).

              "- Handle Credit Card Payment"

              This is ideal as again the rules are not determined by you and are naturally isolated. If it cannot reach the payment server throw an exception as that is serious and should be forcibly handled higher up, if the payment details are wrong just return false and do the normal sorry your details are wrong routine. That is all it has to do to communicate to the rest of site. Something like that should be pluggable into anything and when learning OOP is ideal as an excercise.

              Same as flickr/ google calender API stuff.

                MPB001 to the rescue!! 🙂

                mpb001;10922874 wrote:

                "But my fear is that I have to do all this fancy, heavy-duty OOA/OOD and fill my apartment with hundreds of UML diagrams - and crazy theory - before I can start building any application?"

                That is more waterfall( Big Design Up Front http://en.wikipedia.org/wiki/Big_Design_Up_Front ) than OOP. It is not actually really indicative of OOP as a whole, it is a project management approach. Get everything in stone and agreed with a client before building and then the outcome has to match that spec exactly. Problem with that is the client can often get what they asked for not what they wanted( change becomes very hard and causes frictions, possibly legal as both sides see the document differently ).

                In iterative development emergent design is used( http://en.wikipedia.org/wiki/Iterative_and_incremental_development ).

                I understand - and agree - with what you are saying. (Remember, my background is with RUP.) And while I am a big proponent of planning, I am also a big proponent of Iterative and Incremental development.

                At the same time, you have to a general direction, framework, orientation and approach in order to tackle anything.

                When it comes to thinking in OOP terms - versus my POP background - I have virtually no frame-of-reference, thus my insecurities!

                The biggest thing I want to avoid is writing discombobulated spaghetti code, wrapping it in Classes, and calling it OOP!! (It has been my observation, that this happens all too often, especially with PHP.)

                If you are going to write OOP, one should make a reasonable attempt to understand what OOP attempts to improve over using POP, and then write reasonable well-thought-out code!

                mpb001;10922874 wrote:

                "
                Business-Logic Classes??
                - Calculate Sales Tax
                - Estimate Delivery Date
                - Manage Inventory
                - Handle Refund
                - Recommend Products
                "

                Yep you get the right idea... You could sit there today and write something that calculated sales tax with no other part of the site done as it has its own set of rules which have to be adhered to( the government makes it up ).

                Okay, good, so I am at least on the right track?!

                mpb001;10922874 wrote:

                "- Handle Credit Card Payment"

                This is ideal as again the rules are not determined by you and are naturally isolated. If it cannot reach the payment server throw an exception as that is serious and should be forcibly handled higher up, if the payment details are wrong just return false and do the normal sorry your details are wrong routine. That is all it has to do to communicate to the rest of site. Something like that should be pluggable into anything and when learning OOP is ideal as an exercise.

                Okay, again, so that is the way I should be envisioning things?

                It would seem to me that I would write a handful of Use-Cases for my e-comemrce site, and then break each one down and relate it to OOP Classes.

                Any other comments or perspectives are welcome. 🙂

                Amy

                  At the same time, you have to a general direction, framework, orientation and approach in order to tackle anything.

                  Frameworks in PHP usually don't have to be that big or complicated. Normally they just start off following a front/page controller pattern that forces a single point of entry and then knows what object/workflow to initiate by a value in a $_GET.

                  With your lists you were generating with things such as the tax thing you were showing you had the right idea because you are thinking in small components( not god objects ) versus convuluted chains of battling actions.

                  "When it comes to thinking in OOP terms - versus my POP background - I have virtually no frame-of-reference, thus my insecurities!"

                  Yep it is hard. The trick is keep the classes as small as possible. The bigger they are the more tangled they can be and harder to fix when they go wrong. We'll go onto self imposed code metrics in a minute. No code is perfect and you'll just have to get used to being imperfect. Make yourself a t-shirt that shouts "REFACTOR MERCILESSLY" and wear it at all times you write code. Eg. Whenever you see those arrows start (http://www.codinghorror.com/blog/archives/000486.html ) time to refactor.

                  "discombobulated"

                  Needed Google for that 🙂

                  "The biggest thing I want to avoid is writing discombobulated spaghetti code, wrapping it in Classes, and calling it OOP!! (It has been my observation, that this happens all too often, especially with PHP.)

                  If you are going to write OOP, one should make a reasonable attempt to understand what OOP attempts to improve over using POP, and then write reasonable well-thought-out code!"

                  Yep I agree on the PHP front, but that is only really to do with that PHP does not enforce it. In pure OOP languages due to it is forced a lot of people probably just hum along with the band actually never really asking why is it like this. In PHP due there has to be a conscious mind shift and it has to be more actively learnt, and also causes all these discussions which I think is good. The fact you recognise it is a plus in itself. Normally in an organised team there are common metrics imposed, say 90% of the time those metrics are always valid. Even though you are not working in a team you impose some metrics on yourself because after they are set you have a very easy warning sign that things are getting a bit out of control.

                  Say
                  300 lines is a very large class
                  30 lines is a very large method
                  10 properties is a lot of properties
                  20 methods is a lot of methods
                  2 levels of cyclomatic complexity per method( though if you are proponent of single return that would probably be 3. I was single return now I see it as a waste of a level of indentation. Flat code is prettier. )

                  Whenever you start hitting that level just ask a conscious question what might you doing wrong. Say 10% of classes may break these rules but they are allowed to if they have a good reason.

                  At the PHP Con this year Aral Balkan did a talk a and in it he was saying about a job where he went in as a consultant somewhere and he was faced with a developer in the state of analysis paralysis on where to start. His recommendation was just build something, and even though I didn't agree with him as it could be misinterpreted to "Just go into Notepad and build something that will make someone else cry for the rest of their life my army of flying monkeys", I think in some rare cases it is a worthwhile professional notion. He was an excellant speaker though and I have a heavy respect for people who can do it that well. It is not always the message but the artistry of how the message is delivered that is important. I think your project management head is having a fight with your developer head and causing analysis paralysis. You need to write something/anything then ask for critique.

                  Okay, again, so that is the way I should be envisioning things?

                  It would seem to me that I would write a handful of Use-Cases for my e-comemrce site, and then break each one down and relate it to OOP Classes.

                  Any other comments or perspectives are welcome.

                  Do whatever works best for you. When I worked in the media industry I just let the designers battle it out with the clients, go to some of the meetings and then get a wall of A3 printouts and their JPEG forms for measurments/clour stuff. Then I would isolate everything into relational data by seeing what links to what, what is shared between each page and do it component by component. If I saw a flaw or I had a question I would ask the client for confirmation or advise them against it. Never any official use case stuff but as clients are quite often visually minded they had unwittedley created and agreed. Just by going can we have the banaba link to the monkey etc.

                  Personally I would use wireframes for this then make the use cases from the wire frames.
                  Eg. http://dub.washington.edu:2007/denim/

                  It will help solidify what you want plus it might be fun to get a bit less formalised and more creative. Whatever the beret wearing frillies( designers ) say softwware development is a creative process.

                  Also you can use something like http://dev.mysql.com/downloads/workbench/5.1.html to design the database if you are using MySql.

                    If you have any spare time (hah!) you might want to poke around at some of the literature on eXtreme Programming (XP). It takes the idea of iterative analysis/design/implementation/testing to -- well -- an extreme. In a nutshell, you start with the simplest thing that gets the basic job done, then refactor (mercilessly 😉 ) as needed to adjust to the changing design (and changing/discovered requirements).

                    I'm not saying it's necessarily something you specifically need to study and embrace, just the idea that not everything has to be perfect to start with, just "good enough." You need a good enough overall plan, then a good enough design on whichever part you decide to work on first, a good enough implementation, then figure out where you're at and what needs to be done next.

                    As long as you build each piece with relatively decent OOD/OOP, keeping your classes loosely coupled, when you find you need to change something, you (hopefully) can keep those changes highly localized and relatively simple. You just keep incrementally making things a "little more good enough" until the whole thing is good enough.

                    Did that make any sense? :rolleyes:

                      Sorry for the late response... I have been mired in a computer and data disaster the last several days?!

                      mpb001;10922890 wrote:

                      At the same time, you have to a general direction, framework, orientation and approach in order to tackle anything.

                      Frameworks in PHP usually don't have to be that big or complicated.

                      You took "framework" in an IT sense - I just mean it in a general sense.

                      Normally they just start off following a front/page controller pattern that forces a single point of entry and then knows what object/workflow to initiate by a value in a $_GET.

                      Can you give me a more detail example of this?

                      With your lists you were generating with things such as the tax thing you were showing you had the right idea because you are thinking in small components( not god objects ) versus convuluted chains of battling actions.

                      Good, so it looks like I am on track?!

                      Yep it is hard. The trick is keep the classes as small as possible. The bigger they are the more tangled they can be and harder to fix when they go wrong.

                      So, it sounds like you are of the school that Classes should be fairly "atomic" in nature and that you just keep plugging them into each other - like a Lego set - to build larger and larger things?

                      As far as "god objects", does that mean that you should get to abstract in modeling your site? For instance, maybe you have...

                      User (parent)
                      Vistor (child)
                      Customer (child)

                      but you avoid things like...

                      Human (grandparent)
                      Animal (great-grandparent)
                      Living Creator (great-great-grandparent)??

                      We'll go onto self imposed code metrics in a minute. No code is perfect and you'll just have to get used to being imperfect. Make yourself a t-shirt that shouts "REFACTOR MERCILESSLY" and wear it at all times you write code. Eg. Whenever you see those arrows start (http://www.codinghorror.com/blog/archives/000486.html ) time to refactor.

                      Yah, I'm all for constantly improving things. (It is one thing to remove the wood clapboards and replace them with vinyl siding. But my original fear is wanting/needing to move the driveway after the concrete has dried?! Demolition is not my thing!!)

                      Thanks for the link!

                      "discombobulated"

                      Needed Google for that 🙂

                      All the "cool" boys and girls hang out over at www.dictionary.com every day! 🙂

                      Yep I agree on the PHP front, but that is only really to do with that PHP does not enforce it. In pure OOP languages due to it is forced a lot of people probably just hum along with the band actually never really asking why is it like this.

                      I say be a rebel and always question authority!! :evilgrin:

                      In PHP due there has to be a conscious mind shift and it has to be more actively learnt, and also causes all these discussions which I think is good.

                      Yah, I love getting philosphical about code and life!

                      The fact you recognise it is a plus in itself.

                      Thanks!!

                      Normally in an organised team there are common metrics imposed, say 90% of the time those metrics are always valid. Even though you are not working in a team you impose some metrics on yourself because after they are set you have a very easy warning sign that things are getting a bit out of control.

                      Okay.

                      Say
                      300 lines is a very large class
                      30 lines is a very large method
                      10 properties is a lot of properties
                      20 methods is a lot of methods
                      2 levels of cyclomatic complexity per method( though if you are proponent of single return that would probably be 3. I was single return now I see it as a waste of a level of indentation. Flat code is prettier. )

                      Whenever you start hitting that level just ask a conscious question what might you doing wrong. Say 10% of classes may break these rules but they are allowed to if they have a good reason.

                      That seems like a good way to approach coding Classes. (And those little "rules-of-thumb" are what i am looking for. Life is easier when it is a "science" and not an "art"!)

                      At the PHP Con this year Aral Balkan did a talk a and in it he was saying about a job where he went in as a consultant somewhere and he was faced with a developer in the state of analysis paralysis on where to start. His recommendation was just build something, and even though I didn't agree with him as it could be misinterpreted to "Just go into Notepad and build something that will make someone else cry for the rest of their life my army of flying monkeys", I think in some rare cases it is a worthwhile professional notion. He was an excellant speaker though and I have a heavy respect for people who can do it that well.

                      Public speaking is EASY - learning OOP is tricky! 😛

                      I think your project management head is having a fight with your developer head and causing analysis paralysis.

                      So my PMP certification is working against me, huh?! 🙂

                      You need to write something/anything then ask for critique.

                      This is true.

                      Well, once I get my new computer working - HDD crashed on a few day old PC - and then get my data off my old, dying PC, and get everything backed up, then I'm off to finish reading my OOP PHP book and maybe one more, then it is time to get down to coding (after I write my requirements and Use-Cases)!!

                      Do whatever works best for you. When I worked in the media industry I just let the designers battle it out with the clients, go to some of the meetings and then get a wall of A3 printouts and their JPEG forms for measurments/clour stuff. Then I would isolate everything into relational data by seeing what links to what, what is shared between each page and do it component by component. If I saw a flaw or I had a question I would ask the client for confirmation or advise them against it.

                      You think like I do. I always approach system design from a data standpoint, first. (It's the database person in me!)

                      Never any official use case stuff but as clients are quite often visually minded they had unwittedley created and agreed. Just by going can we have the banaba link to the monkey etc.

                      Well, for me, I am a BIG Use-Case advocate.

                      Personally I would use wireframes for this then make the use cases from the wire frames.
                      Eg. http://dub.washington.edu:2007/denim/

                      It will help solidify what you want plus it might be fun to get a bit less formalised and more creative. Whatever the beret wearing frillies( designers ) say softwware development is a creative process.

                      Well, I will look into that and I do plan on doing lots of "mock-ups" which is closer to your Agile world.

                      Also you can use something like http://dev.mysql.com/downloads/workbench/5.1.html to design the database if you are using MySql.

                      Thanks for all of the links.

                      Yah, having a tool where I can do ERD's would be great. (One reason I got so hooked on MS Access in years past!)

                      While my computers died this weekend and my hands were tied, I did lots of Googling on open-source software. (Found a plethora of things I will share down the road for anyone who cares!!)

                      One open-source project that seemed apropos was this UML CASE tool:

                      Argo UML (http://argouml.tigris.org)

                      I am not sure if it has ERD capabilities in it, but it looks sweet for OOP stuff! 🙂

                      whew

                      Okay, THANKS for the awesome response!!

                      Amy

                        NogDog;10922891 wrote:

                        If you have any spare time (hah!) you might want to poke around at some of the literature on eXtreme Programming (XP). It takes the idea of iterative analysis/design/implementation/testing to -- well -- an extreme. In a nutshell, you start with the simplest thing that gets the basic job done, then refactor (mercilessly 😉 ) as needed to adjust to the changing design (and changing/discovered requirements).

                        Yah, I am vaguely familiar with XP. (I actually read a book on it a few years ago while I was becoming a RUP/Use-Case zealot!)

                        I just haven't had the time to dive back into it, but I am interested in the concepts.

                        I'm not saying it's necessarily something you specifically need to study and embrace, just the idea that not everything has to be perfect to start with, just "good enough."

                        Tell that to a perfectionist?! :p

                        Ironically, the big thing that attracts me to Use-Case Modeling - especially since I learned how to do it CORRECTLY - is that it focuses on "mini-sprints" and also emphasizes "Good Enough" so I completely follow you.

                        I say I'm big on RUP - but to clarify - my love of RUP is the Use-Case nd Iterative portion. I am in no ways a "Rational" gal - read commission driven IBM employee - nor a "big, clunky framework" person. So I am closer to being "Agile" than some may think?!

                        At the same time, I constantly preach the statistics where changes in design cost 1/100 that the same changes do in Testing!

                        You need a good enough overall plan, then a good enough design on whichever part you decide to work on first, a good enough implementation, then figure out where you're at and what needs to be done next.

                        You are correct - again - and thanks for the reminder!!!

                        As long as you build each piece with relatively decent OOD/OOP, keeping your classes loosely coupled, when you find you need to change something, you (hopefully) can keep those changes highly localized and relatively simple.

                        Can you explain what you mean by "loosely coupled Classes"??

                        You just keep incrementally making things a "little more good enough" until the whole thing is good enough.

                        I'll give it the "ol' college try"!!

                        Did that make any sense? :rolleyes:

                        You almost always make sense, NogDog. Thanks (again)!!

                        Amy

                          "Loosely coupled" is more or less the same thing as "modularity" or whatever else you want to call it. Loosely coupled code is code where when you need to change something in one area of the code, there should be no cascading effect that causes you to have to change other areas of the code to accommodate that change (along with a fear that you didn't think of every place that might have been impacted by that change).

                          One of the benefits of good OOD/OOP is that when done properly it inherently tends to create loosely coupled code: changing the details on how Foo::bar() operates should ideally have no effect on any other class that happens to use the Foo class.

                            sneakyimp;10922564 wrote:

                            I also find that it's important to have ONE FILE that you can modify to change the behavior of every single page on your site.

                            I could see that your comment comes from years of experience,
                            but wouldn't that constitute heavy coupling?
                            or is that just the norm for php applications? (I'm new so I'm just curious)

                              NogDog;10923137 wrote:

                              "Loosely coupled" is more or less the same thing as "modularity" or whatever else you want to call it. Loosely coupled code is code where when you need to change something in one area of the code, there should be no cascading effect that causes you to have to change other areas of the code to accommodate that change (along with a fear that you didn't think of every place that might have been impacted by that change).

                              In other words, the exact opposite of what Microsoft has done with its operating systems over the last 15 years... 😃😃

                              Amy

                                potatoCode;10923151 wrote:

                                I could see that your comment comes from years of experience,
                                but wouldn't that constitute heavy coupling?
                                or is that just the norm for php applications? (I'm new so I'm just curious)

                                I may be working against the grain a bit in saying this, but I'm of the opinion that in real life, perfectly loose coupling isn't always possible. In practice, it takes a lot of work to keep classes separated. Classes nearly always depend on other classes for some bit of functionality and you have to pass a reference to instances of these other classes through constructors or assignments or method arguments, etc. Furthermore, classes each have their own unique topography in the form of methods and properties so when you use them, you make certain assumptions about how they work and this in turn affects the classes you write that make use of them. The extra work to keep the coupling as loose as possible usually pays off when you need to re-use the class in some other project. In a given project, I often find myself wondering why I bother.

                                As for the single-file-that-changes-everything, I don't think the term of coupling applies at the top application level? Think of it as a config file for your entire application. You find this in nearly every major software project. Apache has one. PHP has one. MySQL has one. Etc.

                                You have to have some level of code that is not itself a class but makes use of classes. I guess I'm saying that some part of your PHP application must be procedural or you won't have any code to take advantage of all your beautiful, loosely-coupled classes. I think this makes sense when you consider that you typically write an application to solve some new problem. As far as I know, nobody has written the perfect loosely coupled god-object class that can be used to perform all the functions of any arbitrary application. And, if someone had, it would need to be instantiated somewhere:

                                $mySkynet = new SkyNet(
                                    $GLOBALS,
                                    $_SERVER,
                                    $_GET,
                                    $_POST,
                                    $_FILES,
                                    $_REQUEST,
                                    $_SESSION,
                                    $_ENV,
                                    $_COOKIE,
                                    $php_errormsg,
                                    $HTTP_RAW_POST_DATA,
                                    $http_response_header,
                                    $argc,
                                    $argv
                                );
                                $mySkynet->go(); // NOTE this may have negative consequences or unintended behavior
                                

                                  I might consider a config file to be a sort of user interface, where the user is the site admin. So from that viewpoint a single config file makes sense as being a much better user interface than a bunch of instructions telling the admin about settings he has to make in a couple dozen class files. :rolleyes:

                                  The trick would then seem to be to implement that configuration data in a "loosely coupled" way within the application code itself. Perhaps this could be via a "registry" pattern class that is populated from that data. Or the data itself could be a set of constants within an interface definition which is then implemented by any class that needs them (or several interfaces if you want to split them up into logical groupings).

                                    NogDog;10923204 wrote:

                                    The trick would then seem to be to implement that configuration data in a "loosely coupled" way within the application code itself. Perhaps this could be via a "registry" pattern class that is populated from that data. Or the data itself could be a set of constants within an interface definition which is then implemented by any class that needs them (or several interfaces if you want to split them up into logical groupings).

                                    That's a good way of thinking about it. It never occurred to me to use the 'interface' concept to apply to a config file. That way, it would be obvious in the class which implements the interface that the class depends on said interface and we can perhaps stop whining about our loose coupling being violated. I've never done this. Can you define constants in an interface that can be used in a class that implements the interface? I'm not so sure you can. Maybe in an abstract class? I suppose I should test this.

                                    We should acknowledge the fact that our coupling is loosened (is it me or does this sound kinda sexual?) when we use a centralized config file and by loosening it we have achieved a great deal of convenience from a maintenance perspective. Trying to cram the config file idea into some kind of OOP structure seems more than a bit forced to me. I like to define a file called config.php that contains all of the values that must be changed when you install an application or move it from one server to another. It's where I go when things change (e.g., new mail server, mysql server, different domain, etc.). Invariably, I end up with some kind of db class that gets instantiated using my config constants. E.g.:

                                    config.php

                                    define('MYSQL_HOST', 'localhost');
                                    define('MYSQL_USER', 'sneakyimp');
                                    define('MYSQL_PASS', 'my_password');
                                    define('MYSQL_DB', 'my_db');
                                    

                                    somefile.php, typically procedural code access directly via apache or included by a file accessed directly via apache:

                                    try {
                                      $db = new DBObject(MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB);
                                    } catch (Exception $e) {
                                      trigger_error('Drat, something happened:' . $e->getMessage());
                                    }
                                    

                                    From there, the looseness of my coupling quickly degrades because most of my other classes end up using the $db object or some other class that uses the $db object.

                                    $foo = new Foo($db, 'alpha', 'beta');
                                    $foo->bar();
                                    
                                    $bar = new Bar($foo);
                                    $bar->foo();
                                    

                                    On the one hand, the code within the Foo class makes a lot of assumptions about the $db object it receives via constructor. On the other hand, it makes no assumptions at all about the variable name I happened to choose at the global level so in somefile.php I can name my $db var anything I want and the code within Foo doesn't have to change because I pass the var anonymously via constructor. Additionally, the class Bar is relieved to be isolated from the particulars of my $db object by the valiant efforts of class Foo.

                                    A registry pattern is a valuable thing for keeping your global namespace clean, but classes that use said registry make assumptions about what you choose as identifiers for your various registered values. Using one results in tightened coupling for your classes.

                                    Ultimately, creation of these OOP structures takes time which you may not have available. In some cases choosing good OOP practice over procedural styles is kind of like choosing to re-plumb your entire house versus having the plumber snake the drain one more time. Over the long term, replumbing might save you money because the plumber doesn't have to visit once a month. If the clog was just your now ex-roommate using too much toilet paper, then the quick fix may be justified.

                                      NogDog wrote:

                                      The trick would then seem to be to implement that configuration data in a "loosely coupled" way within the application code itself. Perhaps this could be via a "registry" pattern class that is populated from that data. Or the data itself could be a set of constants within an interface definition which is then implemented by any class that needs them (or several interfaces if you want to split them up into logical groupings).

                                      If your config interface is comprehensive enough (i.e., it allows all the access that the rest of the application needs), then it shouldn't matter how that interface is actually implemented; one config class might use serialised session data, another might use an XML file, another might pull user-specific preferences from the database. Yet another may just be a stub that produces plausible config data for testing purposes.

                                      Interfaces play a key role in decoupling components. Roughly speaking, you figure out what the interfaces ought to be during the design phase, and once that's more or less clear you can start filling in the implementation behind each one without having to think about any of the others.

                                        9 days later
                                        sneakyimp;10923213 wrote:

                                        From there, the looseness of my coupling quickly degrades because most of my other classes end up using the $db object or some other class that uses the $db object..

                                        When I first started doing OOP I took this approach more. Though over time a layered approach took over more( http://en.wikipedia.org/wiki/Multilayered_architecture ). Layers are similar to tiers, but they are operationally closer, where as tiers can be remote from one another. Replace the word tier with layer (http://en.wikipedia.org/wiki/File😮verview_of_a_three-tier_application_vectorVersion.svg)

                                        In a multi layered system the data layer is the only part that needs knowledge of where the data is coming from. It could be from a database, it could be from an XML file. By injecting a dependancy when not needed the actual implementation of data access gets scattered through all layers.

                                        All resource/service activity is kept at the same level of operation returning the expected formatted data to the Logic layer which glues it all together as all decision making is kept firmly at the Logic layer as it is that layers responsibility.

                                        A database connection factory that returns singleton instances of adaptors is useful for this. It has it's own configuration file so is kept completely modular for any type of PHP database application and could be contained as a shared deployable module.

                                        In these topics when in comes to coupling you have to take into account the worst forms of operational coupling( 5 hundred line included files with 1 big scope and things coming from everywhere, though 500 line god objects with cross object direct member modification and all of them have references to each other also comes close ) to get perspective of what problem loose coupling is trying to solve and how bad coupling can get.

                                        Dependency injection, while often useful, should probably not cross the walls of the layer it operates in. Like Views in MVC calling the Data layer/Logic layer classes directly.

                                        Exampes to follow, I have hit the 11934 limit.