Jump to content

PDO MVC Framework


skippt
Go to solution Solved by jcbones,

Recommended Posts

I'm trying to build a simple mvc framework to understand. I've heard advice about rolling you own framework but I'd rather learn by
playing with some basic examples since diving into using pre existing frameworks without understanding everything seems daunting to me.

So, I have a controller, model and view. In my database file I'm able to retrieve data using     $result[1]->title as an example, but I'd like to have
that information passed to the view (which is basically just my template file).

I'm not really sure how to do this, I've tried a couple of methods and googled, but I've got conflicting answers.

I'd appreciate it if anyone could point me in the right direction and maybe give advice for best practices for mvc structure since I got a lot of conflicting
answers on that.

I've attached some of the code I'm using below.

Controller.php

<?php
class Controller {
    private $model;
    private $load;
    private $name;
    
    public function __construct($model, $load) {
        $this->model = $model;
        $this->load = $load;
    }
    
    public function index() {
        $name = 'view';
        $this->load->view($name);
        $this->model->index();
    }
}



Database.php

<?php

class Database {

    function getData() {
        $username = 'username';
        $password = '****';
        try {
            $dbh = new PDO('mysql:host=localhost;dbname=db_name', $username, $password);
        } catch (PDOException $e) {
            echo $e->getMessage();
        }

        //PDO Class
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
        $dbh->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);

        $sth = $dbh->query("SELECT * FROM posts");
        $result = $sth->fetchAll(PDO::FETCH_OBJ);
        //print_r($result);
        //echo $result[1]->title;

    }
}


Model.php

<?php
class Model {

    public function __construct(){
        $this->string = "MVC + PHP = Awesome!";
    }
    
    public function index() {

    }

}
Link to comment
Share on other sites

  • Solution

There are many different design patterns for MVC, and you can go as in depth into it as you want.  A simple pattern would be a single entry point for the user, which determines through the controller where to route the user, grabbing the data layer from the model, and sending that data to the same place that it routed the user.

 

<?php
$controller->routeUser();
$data = $controller->model->data();
?>

 

**NOTE** The following is IMHO, nothing more!

 

Now you could take it a lot further than that, but really deep architecture is to much overhead for small or medium projects.  Unless you are doing a "facebook" thing, the upfront coding time outweighs the benefits.  I like the way that CakePHP does things, although, even they are a little deep for smaller projects.

 

I know that more than 10 people here would disagree with me, but that is life. :)

Link to comment
Share on other sites

In my database file I'm able to retrieve data using $result[1]->title as an example, but I'd like to have

that information passed to the view (which is basically just my template file).

So pass it to the view?

 

class MyController {
  private $db
  public function __construct(Database $db, SomeView $view) {
    $this->db = $db;
    $this->view = $view;
  }
  public function index() {
    $this->view->render('view', $this->db->getData());
  }
}
MVC is not rocket-science, it's a simple pattern where you have 2 main actors: Model and View, for example a User object (Model) and the View that renders the form to edit the user's details. In an event-driven arch. the View would notify the Model of the changes (Observer pattern) the user made to the form and thus the Model's data.

 

But since this is not possible due to the whole decoupled client/server thing the data is POST'ed back across HTTP but of course you can't call the Model directly since the Model does not know how to call itself therefor you need a 3rd actor to bind the Model and the View together, called the Controller.

 

I hope this way it makes much more sense.

Link to comment
Share on other sites

I remember Model-View-Controller this way - You separate the Data (i.e., the Model) from the Output (i.e., the View) using the Controller as the agent. An not to split hairs, but MVC isn't "technically" a design pattern. For instance I do mine this way:

 

index.html

<section>

    <?php // Fetch the results and display them:

    while ($page = $result->fetch()) {
    // New instance of Controller, this enables to grab
    // the person who posted their real name or user's name:    
    $postedBy = new Controller($page->getCreatorId());
    // Display the appropiate info:    
    echo '
    <article>
    <div class="blog-styling"><div class="profile-pic-style"><img src="upload/' . $postedBy->displayPic . '" alt="Profile Picture" /></div><h6 class="postedon">Posted: ' . $page->getDateUpdated() . '</h6>       
    <h1 class="style-blog-title">' . $page->getTitle() . '<span class="postedby"> by ' . $postedBy->displayName . '</span></h1>    
    <p>' . nl2br($page->getIntro()) . '  <a class="color-theme" href="page.php?id=' . $page->getId() . '">read more here...</a></p>
    </div></article>
    ';
    }
    ?>
</section>
Link to comment
Share on other sites

An not to split hairs, but MVC isn't "technically" a design pattern.

Design Pattern Definition:

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.

I would say it qualifies.

Edited by ignace
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.