Hello, I'm back again with the 3rd installation of my MVC Framework in PHP series, again apologies that it took so long! Now without further ado, let's get straight into it!
We left of last time having created our index page view.
What I'm going to show you today is how to render an existing page chosen, as well as start with styling our pages with bootstrap and get it looking like a real site. To start, we're going to need to open our Init.php file in our /libs folder. Your file should more or less look the same as last time as so:
class Init{ public function __construct(){ $url = isset($_GET['url']) ? $_GET['url'] : null; $url = rtrim($url, '/'); $url = explode('/', $url); if(empty($url[0])){ require_once BASE_PATH . '/controllers/index.php'; $index = new Index(); $index->index(); return false; } } }
// Check if page exists $file = BASE_PATH . '/controllers/' . $url[0] . '.php'; if(file_exists($file)){ // If it does, require it, and instantiate it require_once $file; $controller = new $url[0]; } else { // Log an error to user }
<?php class Error extends Controller{ public function __construct($error){ parent::__construct(); $this->view->errors = array($error); } public function index(){ $this->view->render('error/index'); } }
<h3>Error Page</h3> <br> <?php if(isset($this->errors)){ foreach ($this->errors as $key => $er) { ?> <p id="error<?=$key;?>"><?php echo $er; ?></p> <br> <?php } } ?>
private function init_error($errors){ require_once BASE_PATH . '/controllers/error.php'; $error = new Error($errors); $error->index(); return false; }
if(file_exists($file)){ // Require file require_once $file; // Instantiate class $controller = new $url[0]; // Check if method is set if(isset($url[2])){ if(method_exists($controller, $url[1])){ // Instantiate class, with specified method if it does exist $controller->{$url[1]}($url[2]); } else { $this->init_error('Method Does not exist'); } } else { if(isset($url[1])){ if(method_exists($controller, $url[1])){ $controller->{$url[1]}(); } else { $this->init_error('Method Does not Exist'); } } else { // Render to view $controller->index(); } } } else { // Log error to use $this->init_error('File does not exist'); }
<?php //define base URL define('URL', 'http://localhost/basic_mvc/');
<!DOCTYPE html> <html> <head> <title>MVC</title> <link rel="stylesheet" type="text/css" href="<?php echo URL . 'public/css/bootstrap.css'; ?>"> </head>
<script type="text/javascript" src="<?php echo URL . '/public/js/bootstrap.min.js'; ?>"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> </body> </html>
<!DOCTYPE html> <html> <head> <title>MVC</title> <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'> <link rel="stylesheet" type="text/css" href="<?php echo URL . 'public/css/style.css'; ?>"> <link rel="stylesheet" type="text/css" href="<?php echo URL . 'public/css/bootstrap.min.css'; ?>"> </head> <body> <br> <!-- Start page container --> <div class="container"> <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">MyMVC</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class="active"><a href="<?php echo URL;?>index">Home</a></li> <li><a href="<?php echo URL;?>about">About</a></li> </ul> <form class="navbar-form navbar-right" role="search"> <div class="form-group"> <input type="text" class="form-control" placeholder="Search"> </div> <button type="submit" class="btn btn-default">Submit</button> </form> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav>
Welcome back! Sorry it's been awhile, but let's get straight back into it!
Last time, we left off with our initial main index.php file in our Controllers folder. Let's take a step forward and go to our libs folder which we created at the start, and let's create a file called init.php within the folder.
Next we're going to create a class from it.
class init{ public function __construct(){ } }
$url = isset($_GET['url']) ? $_GET['url'] : null; $url = rtrim($url, '/'); $url = explode('/', $url); print_r($url);
<?php // Define our base dirctory path define('BASE_PATH', dirname(realpath(__FILE__))); require_once BASE_PATH . '/libs/Init.php'; $init = new Init();
<?php define('BASE_PATH', dirname(realpath(__FILE__))); function __autoload($class){ // This will auto load in all our files from our given lib require_once BASE_PATH . "/libs/$class.php"; }
<?php class View{ public function render($name){ require BASE_PATH . '/views/header.php'; require BASE_PATH . '/views/' . $name .'.php'; require BASE_PATH . '/views/footer.php'; } }
<?php class Controller{ protected $view; public function __construct(){ $this->view = new View(); } }
class Index{ public function __construct(){ echo 'We are in Index'; } }
class Index extends Controller{ public function __construct(){ parent::__construct(); } public function index(){ $this->view->render('index/index'); } }
<h1>I am the Index page!</h1>
if(empty($url[0])){ require BASE_PATH . '/controllers/index.php'; $index = new Index(); $index->index(); return false; }
Today i'm going to show you how to make a bot in twitter from scratch using PHP. The aim of this is for educational purposely only, although i have no doubt in my mind someone will make something novel out of it (for want of a more appropriate term!).
First things first, you will need a twitter account. Obviously. But more importantly you will need a developer account which you can get or upgrade your current account to here: https://dev.twitter.com/
You will also need the following files which can be found on my github page.
From there you will need to sign in form the top right hand corner. Then go to your application and create new application as so.
You will then be directed to a page to name and create your new application. Enter the details you want accordingly (you must currently have a live website to test the script on. If you don't you can try a free hosting account from here: http://www.000webhost.com/ a good starting point for beginners) and create your new twitter application. You will then see a page like this, with actual text mind you and not shoddy black lines drawn in paint!
At this point what you'll want to do is open your favorite IDE or text editor, mine is Sublime Text 2 if you must know. Now using our files we downloaded at the start you should see tmhOAuth.php and cacert.pem. What we need to to is create a new directory and place both files within it. The we are going to make a new PHP file, call yours whatever you wish, in my case i named mine websummit_bot.php. The next thing we are going to do is write some code! Let\'s make a class and include our tmhOAuth.php file.
<?php # Enable error reporting error_reporting(E_ALL); class WebSummitBot{ public function __construct(){ # Require twitter auth file require 'tmhOAuth.php'; # Use the data from http://dev.twitter.com/apps to fill out this info # Notice the slight name difference in the last two items) $connection = new tmhOAuth(array( 'consumer_key' => '', # Your consumer key 'consumer_secret' => '', # Your consumer secret 'user_token' => '', # Access token 'user_secret' => '' # Access token secret )); } } ?>
$parameters = array();
if(!isset($_GET['q'])){ $parameters['q'] = "%23websummit"; } if(!isset($_GET['result_type'])){ $parameters['result_type'] = "recent"; } if(!isset($_GET['count'])){ $parameters['count'] = 25; }
if ($_GET['twitter_path']) { $twitter_path = $_GET['twitter_path']; } else { $twitter_path = '1.1/search/tweets.json'; } $http_code = $connection->request('GET', $connection->url($twitter_path), $parameters);
if($http_code == 200){ $response = $connection->response['response']; $data = json_decode($response, true); # Remove the code for printing the data for now $data = (array)$data; for($tweet_id = 0;$tweet_id < 24;$tweet_id++){ $id = $data['statuses'][$tweet_id]['id']; # [0] in this case is going to be a variable that we can loop through # Here, we want to pass in the id of the tweet that we want to retweet $twitter_path = '1.1/statuses/retweet/'.$id.'.json'; $http_code = $connection->request('POST', $connection->url($twitter_path)); if($http_code == 200){ $response = $connection->response['response']; echo '<br>Sent'; } else { echo '<br />'; echo "Error ID: ",$http_code, "<br>"; echo "Error: ",$connection->response['error'], "<br>"; echo 'Not Sent'; } } } else { echo '<br />'; echo "Error ID: ",$http_code, "<br>"; echo "Error: ",$connection->response['error'], "<br>"; echo 'Not Sent'; }
Hello, and welcome to the first in my series of developing your own MVC framework in PHP. Now to begin, i want to get it out of the way with my own simple explanation of what an MVC actually is, and more to the point how it works before we delve into the code. MVC stands for Model View Controller (as you have no doubt ascertained from a Google search!) which is in its simplest form, a design pattern and one which has taken the business of web development by storm in recent years.
The idea behind the MVC is simple enough your Model handles the data and your business logic. Now you may ask (i know i did), "what really is your business logic?". Simple put, your business logic is how data can be created, displayed, stored, and changed in your application or website.
The View then, is how your data is presented to the user in any format your so desire. Probably the easiest part now that i think of it.
Finally, the Controller is responsible for receiving user requests and calling your appropriate resources (classes, methods etc.).
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*) index.php?url=$1 [QSA,L]
$url = $_GET['url']; echo $url;
class Index{ public function __contruct(){ echo 'We are in Index!'; } }
require '/controllers/' . $url . '.php'; $url = Index();
Hello, and welcome to my blog.
For those of you unfamiliar with me, my name is Cian Gallagher and i am an aspiring web and applications developer currently finishing a computer science degree here in Dublin, Ireland where i am from.
This blog (which was built from the ground up by myself!) will be here to showcase some of the work i have done professionally and in my own time as well as to blog about things that interest me such as programming, gaming, and all things tech really!
Stick around, and expect a lot more to come. In the mean time please follow me on twitter!
http://twitter.com/cian_911