Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to transition to MVC coding?

It's been around 5 months since I picked up a PHP book and started coding in PHP. At first, I created all my sites without any organizational plan or MVC. I soon found out that was a pain.. Then I started to read on stackoverflow on how to separate php and html and that's what I have been doing ever since.

Ex: 
profile.php <--this file is HTML,css. I just echo the functions here. 
profile_functions.php <--this file is mostly PHP. has the functions.

This is how I have been separating all my coding so far and now I feel I should move on and start MVC. But the problem is, I never used classes before and suck with them. And since MVC (such as cakephp and codeigniter) is all classes, that can't be good.

My question: Is there any good books/sites/articles that teaches you how to code in MVC? I am looking for beginner beginner books :) I just started reading the codeigniter manuel and I think I am going to use that.

EDIT: Is it possible to have a MVC organization structure to your coding without using cake, codeigniter, etc? Basically just separate say profile.php into 3 different files(the view, controller, model)

like image 284
ggfan Avatar asked May 17 '10 17:05

ggfan


2 Answers

to answer your question

Is it possible to have a MVC organization structure to your coding without using cake, codeigniter, etc? Basically just separate say profile.php into 3 different files(the view, controller, model)

absolutely...

first file profile.php ( the view, what gets hit by the browser )

<?php
include( 'controllers/UsersController.php' );
$controller = new UsersController();
$controller->profile();
$pageData = $controller->data;
?>

the controller

<?php
include 'models/UsersModel.php';
class UsersController{

public $data;
public $model;

public function __construct(){
    $this->model = new UserModel();
}

public function profile(){
    $this->data = $this->model->findUser();
}

}

the model

<?php

class UsersModel{

public function __constuct(){
    // connect to your db or whatever you need to do
}

public function findUser(){
    return mysql_query( "SELECT * FROM users WHERE users.id =  2  LIMIT 1" );
}
}
like image 145
David Morrow Avatar answered Sep 20 '22 10:09

David Morrow


MVC is just a design pattern. It's not really something you can "code in".

If you like to code in PHP, here is an article regarding MVC in PHP. It has an overview explaining the design pattern, and then an example follows.

like image 31
danben Avatar answered Sep 22 '22 10:09

danben