Does ORM lead to bad coding practices? [closed] - php

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
We're using ORM in PHP on our team, and I've noted in two separate projects that, even though we've specifically talked about good MVC design at length, that ORM appears to be allowing people to do DB queries from the View layer and creating difficult-to-maintain code.
I'm leaning towards the opinion that ORM makes it too easy to make queries under the covers that the programmer doesn't think about. By returning ORM objects to the view layer the programmer is essentially leaking a database connection to a layer that should not have it.
Am I thinking about ORM correctly here? If so, why is it so darn popular? If I'm not thinking about it correctly how should I address these issue?

I'd say that you're not thinking about it correctly. ORM by and of itself does not promote bad practices, at least, not in the way you're experiencing it.
ORM is a tool, just like any other framework, api or whatever, you can use it correctly or not.
It sounds more like the problem is that the developers in your team doesn't have a clear understanding of the MVC pattern. I'd start with addressing that issue first.
I think it's quite a common problem with the MVC pattern that developers tend to use the views and controllers for things that they aren't supposed to do. The reasons might be many, but whenever you work with something like this, I beleieve the problem usually starts with something similar to this thought:
"It such an simple little thing I'll just do it here instead, there's
no point doing it all over there."
Basically when trying to decouple design and business logic there will always be situations when it's easier to implement some piece that actually belongs in the business layer in the presentation layer. It mustn't mean that the developer is bad, but it might show some lack of experience or laziness. I know I've been guilty of this exact thing several times, like when developing for Android (never professionally though :)).
How about trying to figure out some sample-case that uses some of the bad practices that you've noticed and have some sort of coding-dojo where you as a team make that code nice and correctly implemented, and if you have time, show the actual benefits of having stuff where they belong. I'd strongly advice against using actual code unless you've written it yourself or the developer responsible for that code is okay with being mangled in front of other devs. But this obviously depends on the culture in your company and if the developers are interested and open for these kind of things. I personally would love having similar things at my workplace.

I don't know that having small ORM calls in the view layer is necessarily bad. For example, I might have foreach (Category::getAll() as $Category): as the loop to list categories on a page. The connection doesn't leak into the scope of the view (or at any rate it certainly shouldn't) since it is encapsulated by the ORM. I could assign the result of this call in the controller and pass the array of objects to the template (and I certainly will with more complex calls) but imo trivial cases are fine in the view.
The biggest problem with ORMs in my experience is the growth of "n+1" database query counts. Normally a one:many list on a screen can be rendered from a single query, but ORMs make it extremely convenient to use a primary loop with one table, and then to do an individual select for each instance of the secondary table. This is inefficient, but you'll only notice when your database starts to creak with the expanded number of queries it is having to deal with.
The best guard against this is to ask your developers to run a toolbar in dev mode (such as the Symfony2 toolbar, PHP Debug or similar) which shows them the number of queries required to build a screen. When trivial screens start needing more than 50 queries (or whatever ceiling you specify) then they need to refactor.
Also, it's worth choosing an ORM that has a reasonably expressive query syntax, otherwise your devs will be shirking back to "raw SQL" mode, which defeats some of the reasons of having the ORM in the first place. For the same reason - and Daniel makes this point well - offering training to your devs on using ORMs effectively is a great idea.

Doing queries from views is a bad practice. You can do it, but is better doing it through the controller via Ajax Requests or whatever you consider suitable.

Related

Is an image display website better suited for procedural or OO programming? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I have a comics website, http://hittingtreeswithsticks.com, and I guess I'm unclear as to which style, procedural or OO, that it's written in.
Basically, there are several "templates", homepage.php, viewall.php, viewFullSize.php, which call upon various scripts... namely, the templates all include imageDisplay.php, which has several scripts which determine how to query based on which category, tag, or subsite is selected.
I've read a lot about the benefits of OO programming- when it's used and when it's not... but am still having trouble answering this question.
The way I understand the difference between OOP and procedural from an example standpoint is:
OOP: If you have a website where a user can create an object, such as a forum where a user can submit a post... then you'd want to go with OOP because you'd want to allow users to create several instances of the Article class.
Procedural: I went with what I think is procedural because my comics website simply displays comics out to users. A user can submit a comment using DISQUS, or like/dislike. I don't see where I'd be able to fit the OOP paradigm into a simple image display site.
So, the question is:
To use OOP, do you necessarily need to have several objects that would be instantiated? Or are there other benefits I'm missing?
Thanks
Do both.
Just call the procedures "methods", or your methods "procedures".
Objects don't need to correspond to real world objects, it's as much about modularization and moving code into isolated (!) chunks as about "objects".
All in all, a website is not the best to understand OOP. Too little inheritance happening.
Instead, write a simulation. For example, a road with maybe a crossroad and a few drivers driving around.
Start with a stupid driver, then try to allow for subclassing it with different smarter drivers. Or aggressive drivers. And see if they can cause more traffic jams.
Try to start with a problem where you have natural objects that share a lot of traits, and only differ in a few.
Always code OOP. The only reason people ever code procedural PHP is because they're using pre PHP 5.
To answer your question, no. You can have a single object. OOP is just for code organization and the implementation of DRY principals.
OO is normally a better aproach, as long as you document correctly and are aware of class dependencies/herance/hierarquy.
Besides adding a bit of security to your code, an correctly implemented OOP is trully powerfull for adding and upgrading new features, organize code, reuse logic.
As everything is within it's object definition, you always know where and what to look for.
Yes, is kinda tricky at times but it pays.
Non OOP is good practice only in basic methods, small coding.
Something like the "Hello world" :p
Or a non server content dependedence of content or better known as static websites.
For OO you don't require an object to have definition like parametters or whatever.
In your case, you could have an object for db handling, another for top menu bar, another that handle comic book related stuff like sorting, listing...
Basicly wraping everything in it's corresponding place, reusing code more efficiently..
Hope this helped

Structuring own "small framework" in php [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
BACKGROUND / IDEA
I am currently working on a small framework just to improve my php-knowledge. This framework should be very simple (minimizing overhead) and flexible in terms of later expansion.
DIFFERENT MEANINGS
As a result of reading more advanced tutorials, notes of serious php-developers, different class structures (singletons, Singletons, dependency injection, JIT, ...), oop, mvc, routing, caching... and a lot more I find it very difficult to filter "the proper way" (if there is one) as it seems to me that everyone says something different.
Many people praise there opinon as "the best" and say that everything appart from that is evil. In my oppinion there is not a right or false. There are just several ways to achieve one's goal.
WHAT I DID SO FAR
index: ini settings, define constants, call bootstrap (not oop)
booting: autoloader class, namespaces (include files on demand)
static classes: htmlManager, fileHandler, databaseManager, ...
singletons: none
non-static classes: controller, models, views, routes, ...
I know that this is very basic and I did not that much so far but I want to create a solid platform first.
QUESTIONS
Before I want to go any further in my project I'd love to hear your opinion on the things listed below.
How do you organise/structure small or even bigger projects?
What are your experiences concerning simplicity, logic, performance, readability, expandability and reusability of code?
Is there really a "proper way" of coding or it this just interpretation?
Is there anything one should not use because it is already obsolete?
WHAT I DON'T WANT TO HEAR
Forget about a framework or php
Don't do this, don't do that without naming the reason why
Many thanks in prior for every response I get.
I am currently working on a small framework just to improve my php-knowledge. This framework should be very simple (minimizing overhead) and flexible in terms of later expansion.
Go for it.
As a result of reading more advanced tutorials, notes of serious php-developers, different class structures (singletons, Singletons, dependency injection, JIT, ...), oop, mvc, routing, caching... and a lot more I find it very difficult to filter "the proper way" (if there is one) as it seems to me that everyone says something different.
That's because some people don't have an understanding why something should be solved in a certain way or why something is terrible practice, but they see something on some framework and they think it's the best thing since sliced bread.
Although opinions may differ, you cannot argue with clean code and proper OOP if that is what you are after. In proper OOP singletons and statics have no place. Also what most people call MVC is actually some wrong view on the pattern (mostly because again they have seen some framework do it some way). Which is not always bad, but it is not MVC.
Many people praise there opinon as "the best" and say that everything appart from that is evil. In my oppinion there is not a right or false. There are just several ways to achieve one's goal.
Not everything that isn't the best is terrible in my opinion. But some stuff is just bad practice. And some pattern are defined in a way to make your applications easier to maintain, debug and test. If you are going to implement some other pattern that's all fine with me, but you will loose the benefits of some other pattern.
Generally speaking the first rule of thumb I use when doing OOP programming is following the SOLID principles.
static classes: htmlManager, fileHandler, databaseManager, ...
These have no place in proper OOP. Amongst others because the will tightly coupling the classes. Which make maintainability, readability and testability a pain.
singletons: none
Good, because they are just a fancy global.
How do you organise/structure small or even bigger projects?
Separation of concerns in both code as structure. One of the pattern can help you with that: MVC, MVP, [MVVM](Model View ViewModel). For me personally I like the MVC pattern the most because it has some nice benefits against other patterns.
What are your experiences concerning simplicity, logic, performance, readability, expandability and reusability of code?
Readability and testablity are the most important.
Right after that SOLID (which is also handled by the first point (overlap))
Is there really a "proper way" of coding or it this just interpretation?
Is there anything one should not use because it is already obsolete?
Performance
Forget about a framework or php
Don't do this, don't do that without naming the reason why
As I stated before: Just go for it. Do it and screw it up! Best way to learn is actually doing it and making terrible mistakes. I think the framework I made 1 year ago (although imho still better than 90% of what is out there) is a proper piece of crap ™.
How do you organise/structure small or even bigger projects?
Many PHP frameworks use the MVC structure.
What are your experiences concerning simplicity, logic, performance,
readability, expandability and reusability of code?
Beside strict following of MVC I would suggest following principles like KISS and DRY. I would not consider performance as a high priority topic. You can get yourself familiar with caching strategies and good algorithms later (general topics, not PHP).
Is there really a "proper way" of coding or it this just
interpretation?
There are some things that could be considered as best practice, you will find many hints on popular frameworks like Zend or symfony.
Is there anything one should not use because it is already obsolete?
You'll have to find out for yourself. You could skip writing a database handling and use ORM libraries like doctrine or propel. You could choose a special template engine for your view-representation like twig or smarty.
Don't do this, don't do that without naming the reason why
I think all long-time PHP programmers started their own framework at least once, there is no argument against it, especially not if you want to improve your knowledge.

Why are dynamic frameworks like this not scalable? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've always had a thing for dynamic code. Code that's really easy to add cool new features to, without doing much work. For that reason, I build lots of dynamic frameworks and use them in my projects. Some are small, some are big.
As an example, I built a small custom error reporting framework that I still use in almost all of my projects today.
Here's a quick example of how it works:
error_reportLibrary.php - This is where all the magic happens. The class and all the methods sits here. This is the file included when the framework is needed.
error_reportConfig.php - This is where my configuration goes (error types, ect). Here's an example of this file, which shall give you a pretty good explanation of how the small framework works:
(the comments in the code should explain what each element does as a setting)
# ------ Main Settings ---------
$error_handlingSettings['errorStat']=true;//set this to false, and I wont display any errors. I don't care what the other errorTypes have to say.
$error_handlingSettings['default_highlight_color']="red";//this is the default highlight color that will be used if no color is defined for a specific errorType
# ------ Open API -------
$error_handlingSettings['open_api']['status']=true;//set this to true and I'll show errors for the Open API
$error_handlingSettings['open_api']['highlight_color']="#0ff";//shall I highlight any errors that occur for this specific type? if so, set this to a color.
$error_handlingSettings['open_api']['onRemoteAddr']=true;//shall I display errors to specific IP addresses?
$error_handlingSettings['open_api']['remote_addr'][]="86.8.168.228";//so I will show to this IP
$error_handlingSettings['open_api']['remote_addr'][]="127.0.0.1";//and this IP
# ------ SQL Core -------
$error_handlingSettings['sql_core']['status']=true;//set this to true and I'll show errors for the SQL Core
$error_handlingSettings['sql_core']['highlight_color']="orange";//shall I highlight any errors that occur for this specific type? if so, set this to a color.
$error_handlingSettings['sql_core']['onRemoteAddr']=true;//shall I display errors to specific IP addresses?
$error_handlingSettings['sql_core']['remote_addr'][]="86.8.168.228";//so I will show to this IP
$error_handlingSettings['sql_core']['remote_addr'][]="127.0.0.1";//and this IP
So as you can probably tell, each error type is simply a different part of the project I'm using the framework on (for example, SQL Core is the database framework I use. So if any db query issues occur, this errorType will be looked at when printing errors).
So for printing errors, this is the syntax:
errorModule::doError("errorType","error messege");
As you can see, there are some extra little things I can do. Like display to certain IP addresses and highlight the error text, which I can confidently say: will not affect the scalability of the framework.
Remember, the above is just an example of the dynamic frameworks I create/use in my projects.
Now, to the question(almost): I've been told by a few of my colleges that dynamic frameworks like the above are terrible when it comes to scalability. Regardless of the fact that they are very maintainable. So if I used the above framework on a web app that got 1M+ requests a day, it would totally screw up...
Now I'm not apposing against their opinion (actually....) but I would like to know why this is? Why is a dynamic framework like the above considered bad for scalability?
I think you're missing the point when creating a 'dynamic framework.'
A lot of my earlier PHP code functioned sort of like this; a class with a bunch of methods and maybe a construct method that set up a state, using globals to track configuration in arrays. These all used a lot of memory compared to a wholly OOP approach; and while yes less memory and faster than an 'off the shelf' solution; nothing compared to the way I design frameworks now.
It doesn't appear you are taking advantage of things like interfaces, abstract classes, both class and interface inheritance and so forth. These types of frameworks do scale because the original code base is so small and take advantage of specific OOP functionality (like PHP 5.x's magic methods.)
Multiply a script that you felt was fast enough running on server that's not taxed very much by say 100 and, you've got problems; and you're running out of memory, hitting pages outs; and things will crawl to the point you're forced to reboot/throw more resources at the server.
Why? Poorly written procedural code that tries to act OOP, even tries to look like it, is just wrapping up old habits in a new package.
PHP is slow and clunky in general. It's high-level, which means each line carries "baggage". It's common that a single line of PHP code will convert to a slew of low-level instructions.
You can still scale 'dynamic' frameworks that rely heavily upon PHP's underlying system, and don't waste a lot of time or memory with high-level abstractions.
In my opinion, large, "convenient" frameworks often cause more problems than they solve once shit hits the fan in a production environment. My favorite teachers always reminded me to K.I.S.S. -- Keep It Simple Stupid.
Of course, If you want truly scalable performance you may want to compile your php with hiphop or write your application in a compiled language like C++ or D.

How important are classes? (PHP) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I dont know much about classes, but have a reasonable knowledge of PHP/MySQL.
But why should I learn classes? I know they are important but what benefits can I see using them that I cant with?
Encapsulation, for one.
Steve Jobs once used a good analogy (it was in an interview). To paraphrase from memory, he said
If I want my clothes cleaned, and give
them to a friend, he will return them
cleaned. I do not care if he had to
get a cab, got a bite to eat or
whatever, I just want to give him my
clothes and have them returned clean.
Also, I found the interview. Interesting read.
Basically, he is saying that he doesn't care about the implementation details. That's what OO can do. Hide all the stuff inside a class through visibility and so forth. If you want a list of files from a folder, you could do
$files = new FilesInFolder('your/path');
$files->getByExtension('*.jpg');
You don't care if it uses glob() or readdir().
Update
As opposed to a file full of global functions such as functions.php: you can group all of the functions to specific tools. For example in the example above, you could have getFiles() and filterFilesByExtension() but these 2 related functions will be in the global scope, not to mention the second one will require you pass the files as an array back to it.
Actually, I've found that it is often simpler to use function-based programming in php than object oriented. There are a lot of ways in which just using function libraries and trying to keep your code simple and direct make your php scripts more maintainable, especially if you minimize state to increase reproducibility.
Objects & classes are one tool that you should get to know so that you can choose between the different options, but certainly not the only choice, now that php 5.3 has first class functions, moving more in the direction of true functional programming is another tool that you could get to know.
Php's background is very function-based, a huge portion of the native language provided is functions and sometimes the square peg of objects doesn't fit in php's round hole.
This certainly wouldn't apply to Java, but php's background is very rooted in functions.
Edit:
Let's be clear, to be effective at php you will have to have a good grasp of objects, because you are going to encounter it frequently, and if you work for other people in php, you'll probably have to write OO yourself on your employer's behalf. So get to know it well. But don't stop at OO and consider it the be-all-end-all solution. In fact, when it comes to dealing with other people's bad php code, I have found solid function-based programming to often be a simpler tool for refactoring and cleaning up bad code.
I would say there are a few ways to write php code:
Bad procedural code (little reusability, probably uses functions, but not well, probably uses objects, but not well).
Good function-based code (maximized reusability, minimized complexities of state, separation of concerns)
Bad object oriented code (large multifaceted objects, complex hierarchies, etc)
Good object oriented code (specific-task objects, clear separation of concerns like MVC)
And eventually, as php 5.3 matures, we'll be able to start throwing in a bit more functional programming into the "good function-based code" category and it will become an even more effective alternative. In the meantime, though, get comfortable with 2 and 4 because you'll need 'em both.
Classes are important when dealing with code reuse, they also provide well organized and cleaner code, in my opinion.
Depending on specific applications/projects you are working on, classes can make sense.
Update:
Also, it might be worth glancing at, and noting that Wikipedia has a section in Class (computer science) called Reasons for using classes which demonstrate a few key points for using classes.
Also, from your previous questions it seems you do a lot of work with PHP and MySQL. To demonstrate how beneficial classes are, you could create a Connection class that handles connecting to your MySQL database, so any changes made to the database you can edit in one single place, (your Connection class) rather than finding all the lines of code when it's called.
One of the main points of object oriented programming (objects and classes) is to make your programs more modular; when you work on one part, you don't have to work on the details of another part of the program. Depending on what kind of code you are writing, this may or may not be important.
A lot of people on a page like this will claim that a) OOP is the only good way to write programs and b) it is desperately needed for any program and/or home-page. I think if you think of what you are writing as a home-page, you probably do not need OOP, unless it's a very large home-page.
OOP is by far the most common programming paradigm, which makes it important to learn, if you want to be a programmer. However, most PHP is not written in an object oriented style and some of it is ok anyway (even though a lot of it is not).
If you think that the PHP that you are writing is hard to manage, learning OOP is probably a good idea, even if you only get the practice. You might even want to try it out in another language like, say, Java or Ruby. It is probably easier to find good books about OOP in those languages.
Classes and objects in PHP make one very important aspect of programming much much easier: abstraction.
Like many languages that have objects in addition to scalar types, objects in PHP simple take the aggregated item concept one step further. Things like arrays/lists let you work with a collection of data as one item. Objects make that just a little easier and also let you have code specific to that collection to manipulate that collection.
How about an example? I was involved in an educational intranet application some years ago. Its prime goal was to track academic progress over time and to do that it has to know about student enrolments, class membership and thus timetables. We needed a data point for a particular scheduled class in time. Initially, it was a list of data parameters passed into functions. Year, term, week, day, period. Then it needed to be returned, as well. Now it was an array. Then we needed specialised functions for manipulating it, mainly turning it into a real time and back again. So I made it an object.
Now, as an object, the conversion routines were thoroughly abstracted away. You could ask the object to convert itself and without the calling code caring or knowing, the object could cache expensive calculations. Code to handle tricky things like daylight savings was written and debugged once. The object just made it so much easier to handle the data.
Much of the PHP code was still function oriented. The startup logic on each page called a dozen functions to get everything going. But there were objects, too, for when the data needed it. And it made a lot of the code a lot simpler and more robust.
As always depends what you have to do, the Object Oriented way can become useful for many reasons:
If well designed increase the order inside your projects that means much more code re-usability, reduce the written code, less time spent in troubleshooting.
Collaboration if you have to work with many other peoples it's much more simple to maintain the code
Modularity it will give you a very good project organization
Encapsulation By implementing classes you can hide the code complexity inside the objects and keep "only" the logic part in the main code.

How different is CakePHP from Ruby on Rails? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I almost never hear the word CakePHP without hearing the word Rails shortly afterwards. Are these two frameworks mainly similar based on how they adhere to the MVC model or do they have other significant similarities/differences?
One of the main attractions of Rails for me is how easy it is to do Ajax. Would that also be true of CakePHP?
CakePHP is like a cheap, bastardized ripoff of Rails. It tries to be like Rails without doing any of the stuff that makes Rails great. It kinda feels similar, I guess.
CakePHP has an Ajax helper that does something similar to the Ajax-related helper methods in Rails, so yes, in some way, it's also true.
But CakePHP is really an exercise in futility: its authors wrote it so they wouldn't have to learn Ruby, even though learning Ruby and Rails together is probably easier than figuring out the monstrous mess that is CakePHP.
(This, coming from somebody who does CakePHP at his day job.)
Since y'all asked, my biggest complaint about CakePHP is how it manages to totally butcher the conveniences of object-oriented programming: sure, it implements the Active Record pattern just as much as Rails does, but it makes you pass around data structures.
I feel like any logical person would implement an ORM using faulting and dynamic loading of properties in to objects, which is exactly what ActiveRecord (the Rails library) does. The whole idea of setting a member variable called $recursive to determine which relationships to load is just plain flawed.
Being based on PHP is pretty fatal, too; you can't do anything with global state, you have to depend on mod_rewrite, you pay the startup penalty on every request. Sure, there's optimizations for any environment you're using, but still. People say Ruby is slow, but my own Rails apps run faster than their CakePHP equivalents, last I checked. I admit to being without data on this.
Worst of all, the bugs in CakePHP just about kill it for me. I could tell any number of stories about
the time we spent two days figuring out why CakePHP refused to connect to the right database host
the time half of our pages went blank because of the memory ceiling from using too many components
the amount of code that lives in our AppController because every component load costs several megabytes of memory
the black art of massaging data structures to make XML output work correctly
how we traced down the blank <javascript> tag that shows up at the end of every page
Cake is laid out much like Rails and obviously takes a lot of inspiration & ideas from it. Cake is a nice introduction to MVC frameworks and rails seems pretty straightforward coming from cake experience.
Ajax is super easy with Cake using the JS helper. In fact everything is super easy. Its a great framework, especially for distributed apps (eg cms's) or any other situation where the ease of hosting a php app is a benefit.
I would see the main advantages of rails being Ruby (and therefore the better OO implementation of rails etc) and the community. Gems (much fewer / less comprehensive cake plugins), training materials online, books (eloquent ruby anyone?) meetup groups etc.
I haven't worked with CakePHP, but my impression of it isn't too good. If you're after a Railslike framework for PHP, I think you may be better off looking into Symfony. It's probably a bit more complicated to get started with, but the whole project seems much better organised than CakePHP.
Of course, take with a grain of salt, since these things are quite subjective.

Categories