views:

36

answers:

4

I am writing a pretty basic php app and have created a pretty big mess of functions to do various things, e.g. display_user_nav(), display_user_list() etc. I want a way to organize these in a logical way. What I really need is something like a ruby module, but I haven't been able to find a php equivalent. I also feel that from a programming standpoint they don't belong in classes, as I already have a User object to contain information for one user, and don't want to have to create and store a new object whenever I want to use them.

What I am doing now:

display_user_table()
display_user_edit_form()

What I kind of want to be able to do (sort of like Ruby):

User_Functions::Display::Table()
User_Functions::Display::Edit_Form()

Any suggestions are appreciated.

+1  A: 

If you are using PHP 5.3+, you have namespaces available.

So you can name your functions (the namespace separator is \):

User_Functions\Display\Table
User_Functions\Display\Edit_Form

However, it seems like using a class for this wouldn't be a bad idea. If you feel that display functions don't really belong to User (the same way many people think serialization methods don't make sense in the target objects), you can create a class like this:

class DisplayUser {
    private $user;
    function __construct(User $u) { $this->user = $u; }
    function table() { /* ... */ } 
    function displayForm() { /* ... */ } 
}
Artefacto
thanks. I am pretty amateur with php, so I didn't really know how to implement namespaces. This is just what I was looking for. I also understand that I should ideally be using a more MVC-like structure to keep things organized, but frankly the project is small enough that is not worth the effort.
Dave
A: 

how about Abstract Classes!? or singletons? thats a good way to organize your code

pleasedontbelong
A: 

Well you could break them out into helper classes for example:

$helper = new UserHelper();
$helper->renderTable($user);
$helper->renderForm($user, 'edit');

The architecture of the helpers could be more complexx and implement a fluid interface or something to that effect depending on how your classes operate.

Another approach might be to attach decorators to your objects to perform these functions.

prodigitalson
A: 

There shouldn't be such functions at all but a template that takes care of all HTML output.

The problem is you are using functions in a wrong way: make a function only to repeat some operations more than once.
Do not use a function for just single operation.

Col. Shrapnel