4

I started making a website, and quickly i found out that my code is a mess. It's been a while since I've been programming in PHP, and since then I learned OOP. Now while making an application in C# or java is pretty easy from this point of view, PHP is giving me trouble.

I used to program everything (in php) just from one line to another, with minimum amount of methods and no classes at all. So how much should be in methods, and where should this classes be?

Example: I have account.php, and i want to update user information. So after checking that someone has sent some data if(isset($_POST[.. what next? I used to just make all the checks like $email=CheckForRisksOrSomething($_POST["email]); and then just update mysql.

This brings me to the question, should I create a class User and what methods should it contain? Also WHERE should this class be saved, assuming that user.php would show you user's profile.

Back to how much should be in classes, should i just use in a file like:

$smth = new Someclass();
if($smth->checkIfSaved()){
    $user = new User();
    $user->updateUser(/* all the $_POST stuff here? */); 
} else {
    $smth->showUserDetailsForm();
}

Also where should Someclass be saved?

So if ayone would give me an example of how to structure the following functionalities (in files, classes and possibly methods).

  • users (registration, login, editing account..)
  • picture with comments of it
  • news (also with comments)
  • administration

This is just an example of course, but i don't want to keep on with my mess and then look at it three days later and just facepalm and wonder what did i write there. Well, i already did that today, that's why I'm asking.


EDIT 24.2.2016

While this is an old question, as suggested look into a framework. While it might take a bit to set it up it increases development speed, code is nice and clean and a lot safer. I personally use Laravel.

Bojan Kogoj
  • 5,321
  • 3
  • 35
  • 57
  • The best way to learn this is by studying some of the many fine existing web frameworks. – webbiedave Jul 07 '11 at 15:59
  • Maybe, but they are usually big and you can get lost quickly and forget what you are looking for. Still, which one would you advise me to take a look at? – Bojan Kogoj Jul 07 '11 at 16:01
  • You can check out the big four: symfony, CakePHP, Zend Framework, CodeIgniter. In addition to being OOP, they also employ the MVC architectural pattern. – webbiedave Jul 07 '11 at 16:06
  • I will be very blunt here, if you have ever worked in Java/C# in real life and have good experience with programming, you should have a basic idea of creating or using an existing framework or design patterns and your problem should be related to syntax not the framework or approach. – Kumar Jul 07 '11 at 16:12
  • @Kumar, unfortunately i learned php way sooner then c++/C#/java so as soon as i come to php I'm completely lost at structuring. Weird, i know. – Bojan Kogoj Jul 07 '11 at 16:18
  • d'oh! from a computer science purists' angle, you are doomed :P BTW, even I am doomed :P – Kumar Jul 07 '11 at 16:21

4 Answers4

3

There's more than one way to skin this cat, but I'll recommend some helpful links and books for you.

Zend's Coding Standards: If you're looking at how to structure, name, etc. your files, then I would look at how Zend suggests to do these things. By following their guidelines, you can create a package that is compatible with somebody else's code using these same methods, as well.

What you will want to do is create a folder specifically for your classes. How do you know when you'll need to make a new class, and what to include? Good question!

If you find yourself running into groups of information that is related, needs to be handled together a lot, or solves a particular problem, chances are you should create a new class that can handle it.

For example, a User class to handle any sort of changes you want to make to a user of your site. Another example is a Role class that can perform tasks (or not) depending on if they're an admin or not. The wonderful thing about Objects and Classes is you can create a User::$role (variable named $role in the User class) that is a Role class. So for instance, you will have a Role object in your User object. From here, your user object can now call to the role object by doing something like:

class User {
    private $username;
    private $role;

    function __construct($username){
        $this->username = $username;
    }
    public function setRole($roleType){
        switch($roleType){
            case "admin":
                $this->role = new Admin(); // contained in another class file
                break;
            case "staff":
                $this->role = new Staff(); // contained in another class file
                break;
            default:
                $this->role = new Visitor(); // contained in another class file
            } // end case
        } // end setRole
} // end Class User

$loggedInUser = new User("Bubba");
$loggedInUser->setRole("admin");
$loggedInUser->role->deleteMessage();

In general, you will want to keep your code structured and separate, so that each class only handles information that it should have, and not do anything more than it should. If you find a class doing too many things, this means you found a good time to create another class to handle this new responsibility. How you tie it all together is generally a problem answered with "design patterns". There is a very good book that covers both programming using objects and classes, as well as using design patterns.

Check out the book "PHP 5 Objects, Patterns, and Practice" by Matt Zandstra, and published by Apress. It's a wonderful book that dips your toes into OOP with PHP!

anw
  • 370
  • 1
  • 5
  • Also, I wanted to make a comment on the code above. $loggedInUser->role->deleteMessage(); would only work if User::$role was set to public, not private. I don't want any confusion, so I'm setting this as an aside comment :D More than likely, you would keep User::$role as private and access it via a "getter" method, and do any further action through there $loggedInUser->getRole()->deleteMessage(); – anw Jul 09 '11 at 03:34
1

It is very hard to tell you how you should do that. There are many different preferences out there. Look at frameworks like Zend, Kohana, CodeIgniter, and so forth.

When I create smaller applications with OOP design, I usually try to follow the following hierarchy:

  • In the index.php include a bootstrap.php.
  • In the bootstrap.php include all classes and the config.
  • Make a classes directory where you can save core functionallity in a core folder.
  • Furthermore, in your classes directory create the two folders controllers and models.
  • In my projects I usually have another folder templates, where all my html files go in (and afterwards get rendered with the Smarty Template Engine).

This is a very simplified approach, but can lead you in the right direction. For your requirements like users, pictures, etc. create a model that contains all the data of one single user.

class UserModel() {
    public $name;
    public $email;
}

And then a controller that can modify this model:

class UserController() {
    public function update($user) {
        ...
    }
}
Ingve
  • 1,086
  • 2
  • 20
  • 39
Sascha Galley
  • 15,711
  • 5
  • 37
  • 51
0

My answer might not be directly answering your questions but might do you lot of good.

Go with a real framework. Don't build websites with code from scratch. It will save you huge amount of time and will force you to use good practices of code separation, really good and clean project structure but again, it will save you time! For many things you decide to implement there there will be a ready solution and the common thing you do (as validate email address) would be done the right way.

I would go with a MVC PHP framework and after having used a lot CakePHP, Zend, Kohana and few others in the past, I would recommend you to go with Yii. Very small learning curve, nice docs, nice big active community and you will be able to port whatever you already have, to it in very small time.

I'm pretty sure for the project you've described that framework will cut your time at least 2 times and in the same time you will have all the things you ask above already solved. I know this from experience, having developed projects from scratch quite some time ago.

ddinchev
  • 33,683
  • 28
  • 88
  • 133
  • I may tray what you suggested, but i still want to know the best way to structure a website. – Bojan Kogoj Jul 07 '11 at 16:08
  • 1
    Well, you will need an MVC structure, check the structure of Yii or CakePHP or CodeIgniter or something they all have the beautiful thing of having a single entry point (index.php file) and structure like this: http://www.pleblanc.com/wp-content/uploads/2010/03/smvc-structure.png But they have also auto-loading, etc that will make using the whole thing quite easier than having you to manage all the includes yourself, probably the bad and more time-consuming way. – ddinchev Jul 07 '11 at 16:21
  • 1
    Here is a whole article on how to build very simple MVC framework yourself: http://www.pleblanc.com/2010/03/building-a-simple-mvc-framework/ – ddinchev Jul 07 '11 at 16:27
0

if you are developing for web, there are high chances that you will be developing a MVC application, simplest MVC framework known to me is CodeIgniter. And I will advice you to use it.

Kumar
  • 5,038
  • 7
  • 39
  • 51