Simple object-oriented exercises for grasping the basics [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 11 years ago.
I'm teaching a few friends some basic object-oriented concepts in PHP and i wanted to give them some real-world examples, but simple, so they can grasp the syntax and the basics of OO. I already gave them the following exercise: create a small class that abstracts HTML form creation. You can create objects for each form field, each type of field has a class. I also have a form class which receives form field objects.
Do you guys have any other ideas of examples or exercises? Thanks!

My blog post about Objects in PHP might be useful:
http://agiletoolkit.org/blog/how-to-use-object-oriented-programming-in-php/
It gives example how to macerate "geometry" classes, triangle, vector, square etc.
When I was learning OOP, I was reading a book with similar examples in C++, but I forgot the name.

A simple exercise I've always enjoyed for getting into an object-oriented way of thinking is to take some simple real-world concept and model it into objects. These concepts can be anything:
A coffee maker
A chicken
A bicycle
etc.
It's very language-agnostic, platform-agnostic, etc. The idea is to abstract out all of the implementation details (things like PHP and HTML) and focus on object-oriented thinking. How does a model for such an object look? What are its attributes? What are its constraints? How does it behave? How does it interact with other objects?
You can effectively design your abstract types by their external observable characteristics and behaviors, their interactions, etc. and then implement those abstractions in PHP or any other language of choice. But the point is to separate out the object-oriented thinking from the specific implementation.

Some things that are usable/practical:
Almost everybody seems to start with a database abstraction library. Very simple to do
Abstraction for different caching libraries (memcache, apc, file cache)
Perhaps a simple router

Try a table generation class, where they receive an array and, depending on it's contents, a table is displayed.

It depends on how much they know already, if they have experience of programming in C++/C and are starting OO, then examples from Databases, forms, vector etc would work, if they have relatively little experience, then you have to start with abstract or real life examples, examples quoted in another reply
A coffee maker
A chicken
A bicycle
etc.
will work great (despite you have mentioned you do not like such examples) in understanding the concept of Object Oriented and the theory behind it. They have to see how everything works together to form a machine, how each component (class) works and interacts (public methods and interfaces) while hiding its own functionality, and providing a set of services to other components (classes).
A very popular examples teachers give is of a radio, where the user doesn't know what is inside the radio and how it works, the user only knows what it does, and the radio makes its features available to the user for use through the buttons on the panel.
These basic examples work well for beginners, and then immediately there should be a programming assignment related to it. Once they understand the basics, programming and application examples instead of abstract examples should be used in my opinion.

Related

PHP: should I be writing all my code in classes? [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've been coding with PHP for a while now, but I've been mainly coding with Functions and raw PHP.
I've started to think that I should be writing my code a whole lot neater and more efficiently. I still can't quite get my head around classes. Should I be writing ALL my code in classes?
For example, one of my scripts is a 'permissions manager' - which allows an admin to edit the permissions of various user groups on the site.
Traditionally, I'd have written this as just a script with functions and whatnot. But would it better to write this as a class? If so, what would this class contain? Would I have a separate permissions class for use around the site, and another for the admin-editing area?
Also the site has an API. Should this all be written as one class?
Also, should I be using public (shared) functions at all?
Thanks!
In my opinion everything depends on how large is your project. I've worked using Magento for a while and it's so big that it must be grouped in classes and packets. It's easier to read code and analyse the structure of project if it's split in classes. Also when you need to modify your project after a month or year then good structure helps to re-learn it.
It is useful to write stuff in Classes when a particular set of functions and variables belonging and/or oriented to the same entity or propose is to be used in different environments. It gives a sense of organization, delegation of tasks and avoids repetition of code.
But in situations where the above is false, it is completely disposable. Theres no point in writing a class to something that will run only in one specific place.
Also, if you only want to have a set of information organized in an object-like style like in $user->name, $user->age etc. you can simply do this:
$user = (object)array(
'name' => 'John',
'age' => 20
);
Yes, in my point of view it would be better to make your code in OOP to be more neat, understandable, readable and also for maintenance it will be more easy,
Please take a look here in this stack :
https://stackoverflow.com/questions/4409824/what-are-the-advantages-of-object-oriented-php
You should approach that question from a different angle. Don't just use OOP because you think you have to.
Ask yourself:
Are there parts of my application that I could reuse in other parts of my application? Then these could be taken out of your script and be put in a function or class.
Is there a scenario where you would like to exchange parts of your code to change the behaviour without having to rewrite major parts of your application? Then classes and interfaces are for you.
Another good argument for using OOP principles is the increased testability of your code. Using interfaces allows you to exchange the actual object for a mock or stub at test time.

Does ORM lead to bad coding practices? [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.
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.

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

Model and backend interface generators for Zend Framework [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.
By doing some research, one of the disadvantages often reported about Zend Framework is the amount of work required to get off the ground. For me this could be addressed if ZF had strong model and backend interface generators like Symfony does. I have been looking for those and here is what I found:
Model generators
http://code.google.com/p/zend-db-model-generator/: looks like official one, based on user feedback, the documentation seems to be awful though.
http://code.google.com/p/zend-model-generator/: seems quite advanced. updated 3 months ago.
https://github.com/inxilpro/Galahad-FE/: not updated in 2 years, looks dead.
https://github.com/codeinchaos/zend-model-generator/blob/master/generate.php: single php file, could be interesting to use as basis and extend as needed.
Backend interfaces
As usual one can use database administration tools
http://www.phpmyadmin.net: quite complete with plenty of new features since 3.5. Hard to extend.
http://www.adminer.org/: single-file backend interface. Quite complete. The use of plugins seems to make extending functionality easy.
Backend interface generators
http://zfdatagrid.com/grid/default/site/crud which comes from what looks like a very active ZF related project: http://code.google.com/p/zfdatagrid/.
http://www.koala-framework.org/: I've recently come across this framework which allows you to create "desktop-like" applications around Zend, which one could use to create a backend interface.
Setting up the interface seems to be quite easy, for instance here is how you would display a form to edit contacts on the same page as you would edit members:
<?php
class MemberContacts extends Kwf_Model_Db
{
protected $_table = 'member_contacts';
protected $_referenceMap = array(
'Member' => array(
'column' => 'member_id',
'refModelClass' => 'Members',
)
);
}
?>
A demo of Koala frameworks is available. To be honest it looks quite impressive.
Q: Which model generators and backend interface (generators) do you use for Zend and why?
I do not use any kind of generator, prepared backoffice or so called scaffolding.
Why I don't use them in a general way ?
These tools introduce a strong dependencies on the way the generated UI is structured, you do not have anymore the power to design it the exact way you want.
They are quite hard to reuse unless you know them very well, they introduce a lot of magic, for example when I create a backoffice using Django I've to set five parameters and I've a backoffice running. Understanding how it works do really need a lot of knowledge on the inner mechanisms of the tool, so updating it can be a real pain.
To my mind there's a strong difference between providing almost complete backoffice application like Symfony, Rails and Django do, and what Zend Framework do: constraining to general framework and libraries.
There is a deliberate choice between something working out of the box and something flexible. I think they tend to aim different needs.
I tend to prefer the Zend Framework approach since I'm not satisfied (nor experienced I've to admit it) with what others offer as an "almost done" UI.
Why I won't ever use them in Zend Framework ?
If Zend Framework doesn't embend such tools, I won't plug what others have tried to build upon it since nothing can guaranty that there won't be any regression on it (and upgrading can be a really good thing since Zend always integrate more and more external services). The power of Zend Framework is its flexibility, by overlapping tools over it, you're going against the philosophy of the product.
It might meet your expectation on really small project, but for bigger one I do really suggest you to build your UI according to your own needs, the backoffice will only take only you one or two weeks more.

Do you know a good book/website about structuring your codes (PHP/ Web 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 11 years ago.
i mainly use PHP and I have been coding using it for a while. My main problem with PHP is that I think as your program gets bigger, it gets harder to maintain your code (probably applies for other things). I want to reduce this complexity in maintaining/modifying my codes. I want to make things modular and have rules when to start a new class or just append to an existing class (for example). I know that there are frameworks out there (CakePHP, Symfony, Rails) but what if I just want to use my PHP and use a hybrid of my own style and an existing style for good code management?
This is not just pertaining to php, this applies to coding in general. Frameworks will only help you organize your mess but if you are new to programming a framework will only organize your messy code.
Some basic ideas to keep in mind aside from undertaking a undergraduate in computer science (which i recommend if you are serious about coding) is to make your code modular.
For example, and this is a simply example to demonstrate the point. If you have a site that generates an html table containing financial data.
(Here are a few scenarios of how to go about coding this ...)
You open up a new screen, financialdata.php, you code from line 1 to line N the code needed to get the financial data from a data source (database perhaps) and then iterate over the financial
data to construct an html table.
You open up a new screen, financialData2.php, you code a function at the top which pulls data from yuor data source and returns an object (array maybe) containing the items. You take this return value and generate your table on this financialData2.php page.
You open up yet another new screen, financialData3.php, you take your database function from financialData2.php and use it to get your financial Data from yoru source. You code another function to generate an html table based on some arguments passed in as parameters. And lastly in your financialData3.php page you display do the following and your page now has a table containing financial data from your data source.
The lesson here: the more modular your code is the better in a lot of ways. You now have a data base function that can get data, and you have a function that will render a table based on a list of items passed in.
You can now create another page and use these functions in different ways, perhaps your data source function has parameters like table and selection criteria. This way you can use the same data function to get data from different tables based on criteria. You now have a VERY basic data abstraction. (Dont let abstraction scare you aware). An abstraction is nothing more then a simplification of something. In this case we have abstracted away the details of how we get data and let our function getData take care of those details.
Please comment/ask questions and we can discuss further but honestly, I do not think one book or web site can teach programming practice like a BS in CSE can through classroom discussion and hands on practice.
Learn Design Patterns:
http://sourcemaking.com/design_patterns (covers the GOF patterns)
http://martinfowler.com/eaaCatalog/index.html (covers POEAA obviously)
Also helpful to increase code quality:
http://phpqatools.org/
A sidenote on frameworks:
while frameworks often do tell you how you should layout your code and folders and stuff, they rarely tell you how to code properly. A framework offers solutions to common problems and that's cool, but if you try to step outside of what the framework already offers in terms of functionality, you are on your own again. That is because frameworks are concrete implementations, while you want to learn about design principles.
This is about code in general (it uses Java/C/.Net for the examples if I remember correctly), but Code Complete's the best book I've read on general code structure. It covers everything, from the nuts & bolts of how to write and organise variables and methods up to program structure. I'm not sure how applicable the examples are to PHP but probably worth a look.
http://www.nettuts.com
everything you'll want to know about PHP and web development.
I like this one: http://www.wrox.com/WileyCDA/WroxTitle/Professional-PHP5.productCd-0764572822,descCd-tableOfContents.html
http://www.amazon.ca/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612
Lots of design patterns explained. But not in PHP. Good for understanding useful design patterns. Support the author by purchasing it.

Categories