Jump to content
Joshinki

MVC

Recommended Posts

Hi,

 

I am still struggling to get my head around MVC. I have drawn something up in powerpoint just to see if my thinking is correct?

 

If you could let me know if this is correct or am I on the right track?

 

Thanks

Josh

 

r3vISC6.png

Share this post


Link to post
Share on other sites

It's kinda correct. Your main controller actually should call the gallery controller, not some view. Inside the controller you would load the view. Something like:

 

<?php
 
$page = !empty($_GET['page']) ? $_GET['page'] : null;
 
switch ($page) {
  case 'gallery':
    $controller = new GalleryController();
    break;
  default:
    $controller = new HomeController();
    break;
}
 
// do something with $controller

Edited by ignace

Share this post


Link to post
Share on other sites

Thankyou for all your replies.

 

@Diversity

Yes this is something custom, I wanted to get my head around this before moving onto a popular framework.

 

@ignace

Thanks for that, So what your saying is load the Gallery Controller, and in the gallery controller -> gallery model -> this would then output the gallery views?

 

How is my template incorporated into this?

 

ie - I want my header/footer to be loaded, and then gallery images to be loaded in the body.

 

Thanks

Share this post


Link to post
Share on other sites

Look, in short, this is how it works:

 

MVC is a concept divided in three keywords, but each keyword covers a LOT in code.

 

Your Model does all the work. Now the Model is not ONE thing, it's everything that is associated with your business logic. Queries, DAO's, Services, Repositories, Factories, Entities, ...

 

Your View only handles presentation. The View is ALSO not ONE thing, it's everything that handles presentation. By presentation I mean in the case of a web application is HTML.

 

Your Controller has actually no real task, but is required to handle a request, since neither the Model nor View are able (nor should they) to do this.

 

Your header and footer are part of the View and this should be handled in the View. A popular approach is the '2-step View' to this problem:

http://martinfowler.com/eaaCatalog/twoStepView.html

 

You can of course use a simpler method if needed, for example:

 

views/gallery/index.php

<?php require APP_VIEW_DIR . '/header.php'; ?>

<!-- Your content here -->

<?php require APP_VIEW_DIR . 'footer.php'; ?>

 

When people first encounter MVC they imagine something very complicated while it's actually really simple:

 

models/gallery/getAll.php

<?php

$db = require APP_MODEL_DIR . '/db.php';

$stmt = $db->prepare('SELECT * FROM gallery');

return $stmt->fetchAll();

 

controllers/gallery/index.php

<?php

$images = require APP_MODEL_DIR . '/gallery/getAll.php';

require APP_VIEW_DIR . '/gallery/index.php';

 

To make this work you need a "Front Controller", what this means is a Controller that is called first. In Java this is the project class with the main() method.

 

For web applications this is whatever file you tell nginx/apache to load as default, usually index.php

 

<?php

define('APP_CONTROLLER_DIR', __DIR__ . '/controllers');
define('APP_MODEL_DIR', __DIR__ . '/models');
define('APP_VIEW_DIR', __DIR__ . '/views');
define('APP_CONFIG_DIR', __DIR__ . '/config');

require APP_MODEL_DIR . '/functions/request.php';

$page = get('page', 'home');

switch ($page) {
case 'gallery':
require APP_CONTROLLER_DIR . '/gallery/index.php';
break;
default:
case 'home':
require APP_CONTROLLER_DIR . '/home/index.php';
break;
}

 

Try to wrap your head around this. You'll see my model is only concerned with model stuff, the view only with view stuff, and the controller just puts the pieces together.

 

This is also true in every framework though it may seem a lot more complicated there.

Edited by ignace

Share this post


Link to post
Share on other sites

I wrote a custom one when I was trying to wrap my head around it.

This is what my index.php page looks like.

<?php
require($_SERVER['DOCUMENT_ROOT'] . '/config.php');
require_once(ROOT . '/common.php');

// set the path separator
define('PS','/');

require_once(APP . '/common.php');

// load system files
require_once(SYS . 'Model.php');
require_once(SYS . 'Load.php');
require_once(SYS . 'View.php');
require_once(SYS . 'Controller.php');
require_once(SYS . 'Router.php');

// load the database
require(DB);

// load routes configuration
require(APP . '/config' . PS . 'routes.php');

// launch application
$router = new Router($routes);
$router->init();
  • Like 1

Share this post


Link to post
Share on other sites

 

I wrote a custom one when I was trying to wrap my head around it.

This is what my index.php page looks like.

<?php
require($_SERVER['DOCUMENT_ROOT'] . '/config.php');
require_once(ROOT . '/common.php');

// set the path separator
define('PS','/');

require_once(APP . '/common.php');

// load system files
require_once(SYS . 'Model.php');
require_once(SYS . 'Load.php');
require_once(SYS . 'View.php');
require_once(SYS . 'Controller.php');
require_once(SYS . 'Router.php');

// load the database
require(DB);

// load routes configuration
require(APP . '/config' . PS . 'routes.php');

// launch application
$router = new Router($routes);
$router->init();

 

Kuddos for writing a custom one to understand it. 99% of the programmers would have used a shitty ready made system to understand MVC and would have been more confused at the end. 

 

You can think of a controller as a way to have all your pages generated from index.php file while having them in a physical state in the /views folder.

 

It is a confusing concept and everyone have a different opinion about MVC.

 

You dont need MVC to write good code.

Share this post


Link to post
Share on other sites

Thank you so much for that response, very helpful!

 

Just so I understand it visually tho, is this correct the way I have drawn it up?

 

9lHF8Cb.png

Share this post


Link to post
Share on other sites

Also, where you have:

$images = require APP_MODEL_DIR . '/gallery/getAll.php';

Could I put this into a model file? and use like:

 

controller/gallery/index.php

<?php
      require_once 'models/gallery/model.php';
      $model = new Model;
      $images = $model->fetchImages();
      require_once 'views/gallery/index.php';
?>

models/gallery/model.php

<?php
    class Model {
        private $pdo;
        
        function __construct() {
            $this->pdo = Database::getInstance();
        }
        
        function fetchImages() {
            $st = $this->pdo->prepare("SELECT * FROM GALLERY");
            $st->execute();
            return $st->fetchAll();
        }    
    }
?>

And then my view/gallery/index.php will be as above on image?

Share this post


Link to post
Share on other sites

I do not encourage building a full production site from my example code merely use it to understand MVC. Once you do, it is recommended to use a framework to learn the finer points of programming and modern programming techniques since MVC is only a small part of building a web application.

 

Other terms you will cross are Object-Oriented Programming, Dependency Injection, Object-Relational Mapping, Design Patterns (Factory, Repository, ..), ..

 

To come back at your example:

 

class Model {
private $pdo;

function __construct() {
$this->pdo = Database::getInstance();
}

function fetchImages() {
$st = $this->pdo->prepare("SELECT * FROM GALLERY");
$st->execute();
return $st->fetchAll();
}
}

 

You will NEVER have a class called Model. Programming is all about assigning responsibility and proper naming. Naming is actually the hardest part of the job.

 

So the responsibility of your "Model" is to:

 

- return a list of gallery images

- add / delete a gallery image

 

So let's settle for now on GalleryManager:

 

interface GalleryManager {
public function addImage(GalleryImage $image);
public function removeImage(GalleryImage $image);
public function getAll();
}

 

At some point we may want to use something different than PDO (Doctrine, Eloquent, ..) to query for our images so we define our manager as an interface. Now for our PDO implementation:

 

class PdoGalleryManager implements GalleryManager {
private $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function getAll() {
// your code here
}
public function addImage(GalleryImage $image) {
// your code here
}
public function removeImage(GalleryImage $image) {
// your code here
}
}

 

We also pass PDO through the constructor and not use a Singleton to fetch it to make it easier to test.

Edited by ignace

Share this post


Link to post
Share on other sites

I do not encourage building a full production site from my example code merely use it to understand MVC. Once you do, it is recommended to use a framework to learn the finer points of programming and modern programming techniques since MVC is only a small part of building a web application.

 

Other terms you will cross are Dependency Injection, Object-Relational Mapping, Design Patterns (Factory, Repository, ..), ..

 

Hi Ignace,

 

Yes I understand that, but it my logic in thinking correct with the image above? I was looking into this design pattern just to help update my future projects easier.

 

Why use a framework over just coding it from scratch as above?

Share this post


Link to post
Share on other sites

 

 

Why use a framework over just coding it from scratch as above?

 

For one thing...modern frameworks are constantly being updated and improved. Another thing is that is what companies want when looking to hire a developer. You should understand the MVC design pattern and how each part works, but then go learn a modern framework.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.