php file... how to spread my code around - php

i am writing a web site with a php on the server side. which i have never used before.
if i get it right it is procedural programming (which is another thing that i have never done)
my question is how to write code:
each procedure should be in a different file?
to separate it to various files?
maybe have one file that receive the request and then dispatches it?
in ojbect oriented things are a lot more clear...
please advise

You can do object oriented programming in PHP, and I prefer to structure it that way.
If you choose to stick with procedural style, 1 file per procedure is not the way to go, imagine if in OOP you did 1 file per method!
Grouping things is better, maybe you have a DB abstraction layer, in OOP you might make it a class, in 1 file. In procedural implementation, you'd have a bunch of procedures in 1 file. Probably named similarly.

There is no strict definition of where things need to be placed in PHP. It's entierly up to you. I suggest you check out the MVC pattern if you are looking to write complex systems.
Feel free to use an object oriented model in PHP, its my style of choice now.

Group related procedures together. One file per procedure is overkill.
There's good advice on this sort of thing in Code Complete. It is a very reputable programming book with good guidelines on how to organize your code.

Personally,i've never jumped in the OO wagon. Old habits die hard. But i experimented with cakePHP which introduced me to the MVC pattern (Model View Controller). Since then i usually follow this structure:
.htaccess << redirects all request URIs to index.php
index.php << the main processing file
_lib/ for configuration files
_lib/classes for all 3rd party classes (such as database abstraction, etc)
_views/
_controllers/

PHP can be object oriented.
But if you are not using it that way, then you just need logical divisions for your functions.
If you have just a few functions, use one include file with all the functions in it.
If your site has several areas, such as 'Membership', 'Library', and 'Resources' and each area uses a number of functions (like 5+), consider creating files for each area, such as: membershipFunctions.php, libraryFunctions.php, and resourcesFunctions.php.

We tend to adopt a structure where we define our objects specific to the site in 1 file. Another file contains all the generic functions (our general library). There's another file defining all the constants and basic structures.
Implementation of the objects and the core site code (database, authentication, etc) is in a common file. This file includes the objects, constants and library files and performs the foundation operations of the site.
Finally, the site's functional groups are placed in their own files for page generation. These files include the common module (file).
Objects are coded to manage themselves so there is little work going on in the functional page files.
We used to split out all the objects into their own files but found it easier to assemble them into 1 general object class definitions file.

I prefer the OO style for PHP 5, and specifically, enjoy the structure that Zend Framework promotes, using PEAR style directory trees, and allowing you to segment your code in a fashion that makes sense, from a OO point of view, and an architecture point of view.
I would delve into the realm of OOAD, but I am pretty sure there are alot of sources on it, one of the best being the Code complete book mentioned earlier in this questions responses.
Look at http://framework.zend.com for a layout of a zend project, particularly the quickstart, I think you might find that it presents you with a good structure to use, even if you dont want to use the Zend Framework itself.

Related

Is there a (simple) way to separate models in pure PHP, and what is a good way of doing it?

What I'm looking for is a way to remove the model from a set of PHP files that make up a website. It's difficult (for me) to explain.
By models I mean models in an MVC sense.
As an example say I have this website:
index.php
about.php
shop.php
checkout.php
All of the above PHP files use the same database. I have separated the views by adding templates using a view.php file that renders the correct template with values passed to it.
I am not looking to use a framework that's already out there. I'm looking at writing my own in some senses, with only the bits I need to use in it.
If anyone would like to explain why this is not necessary, or a better way of doing things, then I'm open to that too.
Thanks in advance.
Writing you own MVC framework will take time, but you will learn a lot in the process. So, if you have the time/resources to do it I definitely encourage you to do so.
In this context here are some small pieces of advise that may help you:
Create your domain model first. I'm assuming that you are going in the OO way, so think about your domain problem and create the abstractions that best represent your problem. Try to keep it decoupled from cross-cutting concerns, like persistence.
Test a lot, test often. Try to test (and run your tests) as you create your domain model. This will be specially valuable when in 6 months you add a new feature and want to make sure that you haven't break anything. If you can separate your domain model from anything external (like the persistence layer or third party web services) the testing it is going to be a lot simpler. Today PHPUnit is pretty much the de-facto standard for unit testing in PHP.
You don't have to write everything from scratch. There are a lot of libraries that can help you to ease the development of an MVC framework, so that you can concentrate on what you really want to develop. For example, you could use Slim to handle the page routing or you could delegate the persistence stuff to Doctrine 2.
It is always nice to analyze how other frameworks solve things. You may want to look at products like Symfony or Kohana or even check how Elgg handles its views system. Also, if you want to check out something radically different you can take a look at Seaside's architecture.
Coming back to your original question, for me the key is to keep things from different layers as decoupled as possible. While I have only used the version 1, Doctrine 2 seems like a good candidate for persistence, since it allows you to create a domain model that is quite independent from the DB. This is a huge step. The second thing is how handle the view system. This is quite developer-taste dependent. For example, I like to model everything with objects, so I like Seaside's approach. On the other hand, Elgg's way of handling views is quite nice and maybe fits better with the way things are handled in PHP. Here is when you may benefit on doing some research before deciding on a route to go.
HTH
As someone who has written his own PHP framework, and with the same sensibility as yours, I can tell you that using a framework is a fine thing to do. That said, start by writing your own - you'll gain greater appreciation for the true structure and utility of a framework.
You'll want to learn about the Singleton object pattern. It is a major differentiator in the kinds of objects you can develop in your framework.
When you have written a few models that your files/controllers (presuming MVC) include, you will begin to see where to abstract a 'base mode' from which others extend (hint: the DB singleton).
When you start pulling in configs and the like, then you'll have your first framework object from which all other bases do their extension.

I have been writing PHP without "classes" for years... what am I missing?

For the life of me, I can't seem to wrap my head around "classes" in PHP.
I have managed to write large, scalable, and popular websites without them.
What am I missing? (And how do I learn?)
Classes will help with code re-use and potentially a very structured application.
Procedural programming can be a lot faster in both development time and execution speed.
OO programming is the more mainstream way but not always the best way. Theres a book called PHP Objects, Patterns and Practice which is a very good read, it covers the basics of classes, why and how to use, abstraction and common design patterns such as MVC. It also covers unit testing and other very good practices for php developers
The point of classes (object oriented programming) is that it bundles data together with the code that operates on it. If done well, this leads to less tightly coupled and thus more maintainable code.
In practice it means fewer global variables (whether used directly or accessed through static factory methods) and lesss passing around of data (i.e. smaller method signatures).
For a concrete example, look at the Mysqli extension: each function has a procedural and an OOP version, and the procedural version nearly always needs to have an extra "link" parameter to give it context, wheras the OOP version gets that context from the current object.
Everybody answered was right you are missing a lot because let's say you have a photo gallery website
instead of writing functions and in the end you end with a lot of them
OOP would be useful in:
Code organization and maintainability
Adds clarity, and reduce complexity
Emphasizes data over procedures
Code modularity
Code re-usability (Believe me you will need that a lot)
Well-suited for databases
I wasn't using OOP before but i started and to be honest not very long time ago, and found it very useful in those points specially in the re-usability of the code
Let's say i have a photo gallery website
i will create a class for users and this class will do CRUD on all of the users table
and a class for the photos to do the CRUD on all of the photographs table
I could also make a class to do all the CRUD for me without specifying on what table
and then use the inheritance to extend all the CRUD in my users class and my photograph class
the point in that is i could only write the CRUD methods once
and then re-use it in all of my other classes
I hope i would have answered your question
IMO, If you do not wish to seperate your htmls & php code; you better not use classes.
You'll need them in a framework environment (not necessarily), and you'll need them if you want to objectify your datas, handle them like that.
but if you're fine without it, then you're just fine :)
When it comes to handle a very complex system, with a lot of different data structures, more than one team members, etc. You and your code need to be organized very well, and you'll need classes.
Good question! You got my upvote!
Straight to the point:
You're missing a whole world!
There are many metaphors to describe it but there's nothing better than practice - you obviously know it after "years" of programming!
Decide on a small project and write it OOP style. Then you'll get the idea.
Take this tip as well: Name your classes as their file names (ex. "MyClass" -> "MyClass.php"). Easy to maintain.
You are probably missing testability: I guess your functions call other functions, which in turn might call another function, right? So you will have trouble testing an isolated function. With OOP you assemble "heaps" of objects and can interchange each object with a "fake" one (called mock or stub) for a test. This way, you can test each functionality in isolation. Think of being able to test you output code without needing a database. Think of testing your controller code (the code which processes the request parameters and decides what action to take) without needing a web server.

small php project is now a huge mess (inside)

I started a small project for me and a few friends to edit a few tables in a multi-database (mysql). Now the project is over several hundred pages and while it looks incredible on the ouside, it is stating to feel cluttered inside. no structure. here is what we have:
3 databases
several hundred tables make up the three DB.
The php project is designed to make it easy to edit these tables instead of manually.
does anyone have a suggestion how to organize the code. I a starting to see repeated includes at the top of files, certain code is starting to repeat (I have functions for the more common ones)
I would like to stay away from "CLASS" type programming (unless you feel this might be best) only because it is an open source project and some of my friends are not that great at php, so want to keep it simple. but for organization, I could go to class style.
my biggest concerns is that the majority of pages (the html part) are tons of cut and paste. so each page is like the other. not sure how to consolidate those efficiently. I think once that part is figured out, the php code will trim up as well.
thanks
I'd go for the Object Oriented style here (or class type programming as you said :)). This will cut your code massively, it will also help if you need to change a function which is on multiple pages rather than changing multiple functions.
Your friends will thank you in the long run, especially when they embrace the goodness of OO.
If you mean "CLASS" as in OOP (Object Oriented Programming) it's definitely something you should consider. Arranging methods in objects is very convenient once you get used to it, when you have discovered the autoloader you'll know why.
You should also take a look on the market of MVC frameworks. MVC stands for Model, View and Controller and is a fairly common pattern amongst applications. I'd recommend looking at CodeIgniter which is very easy to get started with, even without an extensive PHP career.
If you by any chance would stick to the 100% interpreted, in other words: spaghetti and functions. I'd split everything in to files grouped by their area of functionality. Like: media.php, database.php et.c. Take a look at WordPress and the wp-includes folder and see how they've solved it. Good luck!
There are a lot of things you can do differently here. Here are three to get you started:
You're going to have to move to object-oriented programming, especially if you're wanting to go the route of code organization. Keep with the DRY principle at all times.
With that in mind, check out a good frameowrk. I would recommend CodeIgniter. The MVC design pattern will remove a lot of the redundancy in your code if you use it correctly. If you choose to not go down the framework route, I would definitely look at some templating libraries to help you out.
Normalize your database. This will help you remove redundant model code.
My suggestion is to use a XML-like abstraction layer for all the database fields and also use OOP where you can and understand. You can use XML-File-configuration to separate the database-logic and you can use the php XML-extension to parse it. Now if you have your XML-tree in the memory you can parse it again with an engine to output the html stuff. I use this a lot for example TYPO3 uses this too, but not a XML but a very large array. And also using this you can create your own XML-language and attribute. It's a bit like XLST but not as deep but it's better then TYPO3.

PHP: Separating Business logic and Presentational logic, is it worth it? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Why should I use templating system in PHP?
I was just curious as to how many developers actually do this?
Up to this time I haven't and I was just curious to whether it really helps make things look cleaner and easier to follow. I've heard using template engines like Smarty help out, but I've also heard the opposite. That they just create unnecessary overhead and it's essentially like learning a new language.
Does anyone here have experience with templates? What are your feelings on them? Are the helpful on big projects or just a waste of time?
On a side note: The company I work for doesn't have a designer, there are just two developers working on this project charged with the re-design/upgrade. I also use a bit of AJAX, would this have issues with a template engine?
Not only does this practice make the code look cleaner, it also has many long term and short term benefits.
You can never go wrong with organizing code. First off it makes it much easier to maintain and easier to read if someone else has to pick up after you. I have worked with Smarty before and it is nice, it keeps the designers work from interfering with the program code.
Using template systems and frameworks would make it much easier to accomplish tasks. There is a rule of thumb you can follow which is DRY (Don't Repeat Yourself). Frameworks help you achieve this goal.
You may want to look into MVC, this is the model that these frameworks are based off of. But you could implement this design structure without necessarily using framework. Avoiding the learning curve. For frameworks like Zend, the learning curve is much greater than some other ones.
I have found that Code Igniter is fairly easy to use and they have some VERY helpful video tutorials on their website.
Best of Luck!!
Actually it's the business logic that needs to be separated from the views. You can use php as a "template language" inside the views.
You can use ajax on any template engine i think.
Edit
My original response addressed the question whether to use a template engine or not to generate your html.
I argued that php is good enough for template tasks, as long as you separate business logic from presentation logic.
It's worth doing this even for simple pages, because it enables you to:
isolate the code that is the brain of your application from the code that is the face, and so you can change the face, without messing with the brain, or you can enhance the brain without braking the looks
isolate 80% of bugs in 20% of your code
create reusable components: you could assign different presentation code to the same business code, and vice versa;
separate concerns of the feature requests (business code) from the concerns of the design requests (presentation code), which also usually are related to different people on the client side, and different people on the contractor side
use different people to write the business code and the presentation code; you can have the designer to handle directly the presentation code, with minimal php knoledge;
A simple solution, which mimics MVC and doesn't use objects could be:
use a single controller php file, which receives all requests via a .httpdaccess file;
the controller decides what business and presentation code to use, depending on the request
the controller then uses an include statement to include the business php file
the business code does it's magic, and then includes the presentation php file
PHP is a template engine (or if you prefer, a hypertext preprocessor). When HTML is mixed heavily with PHP logic, it does become very difficult to maintain, which is why you would have functions defined separately to build various parts and simply build the page from short function calls embedded in the HTML. Done like this, I don't see much of a difference between Smarty and raw PHP, other than the choice of delimiters.
Separation of concerns is a very important tenant to any type of software development, even on the web. Too many times I have found that people just throw everything into as few files as possible and call it a day. This is most certainly the wrong way to do it. As has been mentioned, it will help with maintainability of the code for others, but more than that, it helps you be able to read the code. When everything is separated out, you can think about easily.
Code Ignitor, I have found, has been the easiest to learn framework for working with PHP. I pretty much started my current job and was up and running with it within a few days, from never having heard of it, to using it pretty efficiently. I don't see it as another language at all, either. Basically, using the framework forces me to organize things in a manageable way, and the added functionality is anlagous to using plugins and such for jQuery, or importing packages in Java. The thought that it's like learning another language seems almost silly.
So, in short, organize organize organize. Keep in mind, though, that there is a level of abstraction that just becomes absurd. A rule of thumb is that a class (or file in our case) should do one thing very well. This doesn't mean it is a class that wraps around print, but takes a string, formats it using a complex algorithm and then prints it (this is just an example). Each class should do something specific, and you can do that without any framework. What makes MVC great, though, is that it lets you organize things further, not just on the single class level, but on the level of "packages", being Model, View, and Controller (at least in the case of these frameworks; there are other ways to package projects). So, now you have single classes that do things well, and then you have them grouped with similar classes that do other things well. This way, everything is kept very clean an manageable.
The last level to think about once you have things organized into classes, and then packages, is how these classes get accessed between packages. When using MVC, the access usually will go Model<->Controller<->View, thus separating the model (which is usually database stuff and "business" code in the PHP world), from the view (which usually takes information from the user, and passes it along to the controller, who will then get more information from the model, if necessary, or do something else with the input information). The controller kind of works like the switchboard between the two other packages usually. Again, there are other ways to go with packaging and such, but this is a common way.
I hope that helps.
Smarty and other php template frameworks really do nothing more than compile to PHP anyway, and they also cache their results in most cases to allow for faster processing. You can do this all on your own, but if you ever look at the compiled templates that Smarty generates, and compare to the original Smarty template you create, you can see that one is far more readable than the other.
I write mostly mod_perl these days and started using templates (HTML::Template) halfway through our ongoing project. If I had to make the decision again, I would use templates right from the start - rewriting later to use templates is kind of tedious, though rewarding because you get nicer and cleaner code. For anything bigger than 2-3 pages in php, I would also use some template engine.
One big advantage of a templating engine such as Smarty is that non-developers can use it to embed the necessary logic that is used on the front-end (one really can't separate logic and display on all but the simplest sites). However, if the developer is the one maintaining the pages then using PHP would be preferable in my opinion.
If you separate out large logic blocks and maintain a consistent patten for looping and for-each flow control statements (i.e. don't use print statements, or only use print statements for one-liners, etc.) Then that should be okay.

How do you write good PHP code without the use of a framework?

Other than standard OO concepts, what are some other strategies that allow for producing good, clean PHP code when a framework is not being used?
Remember: MVC, OOP and tiers are design concepts, not language constructs, nor file-structuring.
For me, this means that when not using a framework, and when there's not different teams for programming and designing; there's no value in using another template system on top of PHP (which is a template language). Also, separating code from layout doesn't necessarily mean doing it on different files.
This is how i used to do for one-off, seldom expanded, PHP web apps:
write a 'general utilities' file, there i put some formatting/sanitising functions, as well as a few DB access functions:
getquery(): given a SQL, returns a result object
getrecord(): given a SQL, returns a record object (and closes the query)
getdatum(): given a SQL, returns a single field (and closes the query)
put all configurations (DB access, some URL prefixes, etc) on a 'config.php' file
write a model layer, either one file, or one for each object you store on DB. There, will be all the SQL constants, present a higher-level API, based on your conceptual objects, not on DB records.
that's your 'framework', then you write the 'presentation' layer:
one PHP file for each page, starts with some simple code to fetch the objects needed, followed by HTML with interspeced PHP code, just to 'fill in the holes'. with very few exceptions, the most complex code there should be for loops. I make a rule to use only one-liners, the ?> should be in the same line as the opening <?php
each data-entry form should point to a small PHP without any HTML, that simply get's the POST data, enters into the DB, and forwards to the calling page.
and that's it. If working alone, it has all the separation of intents you need, without drowning in a lot of files for a single user action. Each page as seen by the user is managed by a single PHP file.
It's even easy to maintain, after a few months without looking at the code, since it's easy to test the app, taking note of the filenames in the URL field of the browser. This guides you directly to the relevant code.
(nowadays, of course, i'm using Django for almost everything...)
If you ever find yourself mixing HTML and code, just STOP. You're, well...
You're doing it wrong! http://dennisjudd.com/albums/cute_cats/wrong_mike.jpg
I'd say pretty much the same as for any other language:
Don't optimise prematurely
Keep methods small
Practise DRY
Practise data-driven programming
Use sensible shortcuts (e.g. ternary operator)
Format your code well so that it can be understood by others
Don't use OO blindly
Always check return codes for errors
Enable the highest warning level and ensure your code doesn't produce any warnings
Be very careful when it comes to typing issues (this goes for all weakly-typed languages). The '===' operator is your friend.
Really this question is quite language agnostic, as it applies to most languages where you choose to "roll your own". Two suggestions I would make would be :
Firstly, just because you aren't using a framework doesn't mean you can't adopt the patterns for segregating code. The MVC pattern is the minimum you should consider when arranging you source code - it makes for a much cleaner and easier to maintain collection of source code, even if the application doesn't entirely follow the routing processes associated with frameworks, having code that "does" things separated out from that which "represents" things is very beneficial.
Secondly, just because you've chosen not to use a full framework, doesn't mean you need to reinvent the wheel. Utilise pre-packaged libraries sensibly in order to solve a specific problems. Two good examples would be a logging framework (log4php) and a front-end rendering/templating solution (Smarty).
Stay away from globals as best as possible :-D
If you really do follow OO concepts, like separation of concerns, your code will be pretty good, but here are a few suggestions:
Framework or not, use MVC.
I can't stress enough how important it is to never mix your logic with your HTML. In an HTML file, PHP should be used only as a template language and nothing more.
Use a DBAL.
Separate your design from your content. A common method for doing this is using CSS heavily and having header and footer files containing the bulk of site layout.
Have a single file for option constants, like DB credentials, FTP credentials, etc.
make sure to follow standard practices of separation of concerns. What this means is try not to mix you business and data layer with your UI.
Even If you don't use a framework, use a template engine. By using templates, you'll seperate the logic and presentation of your application. Then design, code and format the logic part like what you would do with any other language. Make the "designers" design the user interface :)
OO is not strictly necessary: it was possible to write good code in PHP < 5 too. Good procedural code, well separated into files and directories by 'logical distance' should also keep you safe. Notice, though, how this starts resembling OO from afar.
Best thing would be to be consistent: I've seen a project where Smarty was used in most pages except one -the most complex, go figure-.
Take advantage of PHP's in-built extensions - MySQLi for example. As these become more object-oriented the requirement for frameworks becomes less.
For example, I could create a useful TwitterApp by using the following extensions and no actual framework besides a core class to tie instances together.
MySQLi for database (PDO if you need DAL)
SimpleXML for RSS/API reading
Smarty for templating
I might need to make a few helper classes for things like Login but my usual pair of classes (DAL and TPL) are made obsolete by two very well worked extensions.

Categories