<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Okparah Japhet on Medium]]></title>
        <description><![CDATA[Stories by Okparah Japhet on Medium]]></description>
        <link>https://medium.com/@jalleto4rel?source=rss-e8960c45afac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qTtR64epigq00q6X3HgYzA.jpeg</url>
            <title>Stories by Okparah Japhet on Medium</title>
            <link>https://medium.com/@jalleto4rel?source=rss-e8960c45afac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 02:03:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jalleto4rel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build a Twitter Web App (TweetMini) using Object Oriented PHP and a Simple MVC framework]]></title>
            <link>https://medium.com/@jalleto4rel/build-a-twitter-web-app-tweetmini-using-object-oriented-php-and-a-simple-mvc-framework-6f2765a91d77?source=rss-e8960c45afac------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f2765a91d77</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[api-integration]]></category>
            <dc:creator><![CDATA[Okparah Japhet]]></dc:creator>
            <pubDate>Sat, 09 Dec 2017 20:12:04 GMT</pubDate>
            <atom:updated>2017-12-11T20:38:59.811Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DTddn_Rlxd19ue50miCMoQ.png" /></figure><h3>Prerequisites</h3><p>With a basic knowledge of HTML, CSS, Bootstrap and Object Oriented PHP, we are good to go. Knowledge of the Twitter API is not compulsory.</p><h3>Installation</h3><ul><li><a href="https://www.apachefriends.org/xampp-files/5.6.32/xampp-win32-5.6.32-0-VC11-installer.exe"><strong>xampp</strong></a>: <strong>XAMPP </strong>is an easy to install Apache distribution containing MariaDB, PHP, and Perl. Just download and start the installer. It’s that easy. You should have XAMPP or WampServer installed on your machine.</li></ul><h3>What is MVC?</h3><p><strong>M</strong>odel <strong>V</strong>iew <strong>C</strong>ontroller or <strong>MVC</strong> as it is popularly called, is a software design pattern for developing web applications. It divides a given application into three interconnected parts. A Model View Controller pattern is made up of the following three parts −</p><ul><li><strong>Model</strong> − The lowest level of the pattern which is responsible for interacting with the database and maintaining data.</li><li><strong>View</strong> − This is responsible for displaying all or a portion of the data to the user.</li><li><strong>Controller</strong> − Software Code that controls the interactions between the Model and View.</li></ul><p>Popular PHP frameworks that implement an MVC architecture include Laravel and Symfony. So on a good side, we are going to be building a simple MVC framework similar to any of the above.</p><h3>Project Directory</h3><p>Here is a look at our project directory;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*UXiZV3sT6iDFV8JBwCDw4Q.jpeg" /></figure><p>Lets create the project directory and also create the following folders and files.</p><p>In the root directory, we have two folders app and public, and a .htaccess file.</p><p>Now, the app folder contains everything about the application;</p><ul><li>app/config/config.php: holds all our app configuration.</li><li>app/libraries: this folder contains our core MVC libraries.</li><li>app/controllers: folder to hold all our controllers.</li><li>app/models: folder to hold all our models.</li><li>app/views: folder to hold all our views.</li><li>app/.htaccess file: to hide the directory content and prevent access to the app folder from the browser.</li><li>app/bootstrap.php: this file will require our core libraries and config file.</li><li>public directory: this directory contains all our css, js etc.</li><li>index.php: this is the entry point to our app.</li></ul><h3>Lets get started</h3><p>For our custom MVC framework to work, we have to direct/route every request through the index.php file in the public folder and to do this we will rely on the .htaccess file in the root directory.</p><p>Add the following content to the <strong>root/.htaccess file</strong></p><pre>// <strong>root/.htaccess file</strong></pre><pre><strong>&lt;IfModule mod_rewrite.c&gt;<br>  Options -Multiviews<br>  RewriteEngine On<br>  RewriteBase /tweetmini/<br>  RewriteCond %{REQUEST_FILENAME} !-d<br>  RewriteCond %{REQUEST_FILENAME} !-f<br>  RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]<br>&lt;/IfModule&gt;</strong></pre><ul><li>mod_rewrite is an apache module that provides a rule-based rewriting engine to rewrite requested URLs on the fly.</li><li><strong>Options </strong>-Multiviews: this line allows us to exclude the file extension in the url eg. localhost/tweetmini/index.php so we can do localhost/tweetmini/index instead. So when we make a request for localhost/tweetmini/index and localhost/tweetmini/index does <em>not</em> exist, then the server reads the directory looking for all files named index.*</li><li><strong>RewriteBase </strong>/tweetmini/: this is our root url localhost/tweetmini/ without &quot;localhost&quot; so what ever you have after localhost that&#39;s what should be in the rewrite base.</li><li><strong>RewriteCond </strong>%{REQUEST_FILENAME} !-d <strong>RewriteCond </strong>%{REQUEST_FILENAME} !-f the function of these two lines is to look into our public folder and if the requested file is not found then is going to continue to the rewrite rule.</li><li><strong>RewriteRule </strong>^(.+)$ index.php?url=$1 [QSA,L] This line is what allows us to route every request through the index.php, also attached is the ?url=$1 parameter which will allow us to do localhost/tweetmini/index instead of localhost/tweetmini/index.php?controller=users</li></ul><p>Define some constant in the config/config.php file.</p><pre><strong>&lt;?php<br>// app/config/config.php</strong></pre><pre>// App Root<br>define(&#39;APPROOT&#39;, dirname(dirname(<em>__FILE__</em>)));<br><br>// Url Root<br>define(&#39;URLROOT&#39;, &#39;http://localhost/tweetmini&#39;);<br>//Site Name<br>define(&#39;SITENAME&#39;, &#39;TweetMini&#39;);</pre><p>Create some helper functions in <strong>app/helpers/functions.php</strong></p><pre><strong>&lt;?php<br></strong><em>/**<br> * </em><strong>app/helpers/functions.php</strong><em><br> */<br><br></em><strong>function </strong>redirect($page){<br>    header(&#39;Location: &#39;.<em>URLROOT</em>. &#39;/&#39;.$page);<br>}</pre><p>Instead of requiring our core libraries and config file in the <strong>root/index.php</strong> file, we will go ahead and require all the core libraries and config in the <strong>app/bootstrap.php</strong> and then require the <strong>app/bootstrap.php</strong> in our <strong>root/index.php</strong> file.</p><pre><strong>&lt;?php<br>// app/bootstrap.php</strong></pre><pre>// Load Config file<br><strong>require_once </strong>&#39;config/config.php&#39;;<br><strong>require_once </strong>&#39;helpers/functions.php&#39;;</pre><pre><br><br>// Load Core classes<br><strong>require_once </strong>&#39;libraries/Core.php&#39;;<br><strong>require_once </strong>&#39;libraries/Database.php&#39;;<br><strong>require_once </strong>&#39;libraries/Controller.php&#39;;</pre><p>Lets require the <strong>bootstrap.php</strong> file</p><pre><strong>&lt;?php<br>// root/index.php</strong></pre><pre><strong>// start session</strong></pre><pre>session_start(); </pre><pre><strong>require_once </strong>&#39;app/bootstrap.php&#39;;</pre><p>First off, we have to create the MVC Framework on which our Twitter App will be built on.</p><p>Let’s begin with creating our libraries. First let’s create the MVC <strong>Core.php</strong> class, which goes into the <strong>app/libraries</strong> directory.</p><pre><strong>&lt;?php<br></strong><em>/**<br> * </em><strong>app/libraries/Core.php</strong><em><br> */<br><br></em><strong>class </strong>Core {<br>    <strong>protected </strong>$currentController = &#39;Pages&#39;;<br>    <strong>protected </strong>$currentMethod = &#39;index&#39;;<br>    <strong>protected </strong>$params = [];<br><br>    <strong>public function </strong>__construct(){<br><br>    $url = $this-&gt;getUrl();<br>    // Look in Controllers for first value<br>    <strong>if</strong>(file_exists(&#39;./app/controllers/&#39;. ucwords($url[0]).&#39;.php&#39;)){<br>       // If exist, set as current controller<br>       $this-&gt;currentController = ucwords($url[0]);<br>       // Unset 0 index<br>       <strong>unset</strong>($url[0]);<br><br>       // Require the controller<br>      <strong>require_once </strong>&#39;./app/controllers/&#39;. $this-&gt;currentController .&#39;.php&#39;;<br><br>            //Instantiate controller class<br>            $this-&gt;currentController = <strong>new </strong>$this-&gt;currentController;<br>        } <strong>else</strong>{<br>            // Require the controller<br>            <strong>require_once </strong>&#39;./app/controllers/&#39;. $this-&gt;currentController .&#39;.php&#39;;<br><br>            //Instantiate controller class<br>            $this-&gt;currentController = <strong>new </strong>$this-&gt;currentController;<br><br>        }<br><br>        // Check for 2nd part of the url<br>        <strong>if</strong>(<strong>isset</strong>($url[1])){<br>            // Check to see if method exist in controller<br>            <strong>if</strong>(method_exists($this-&gt;currentController, $url[1])) {<br>                $this-&gt;currentMethod = $url[1];<br>                //Unset 1 index<br>                <strong>unset</strong>($url[1]);<br>            }<br>        }<br><br>        // Get params<br>        $this-&gt;params = $url ? array_values($url) : [];<br><br>        // Call a callback with an array of params<br>        call_user_func_array([$this-&gt;currentController, $this-&gt;currentMethod], $this-&gt;params);<br><br>    }<br><br><br>    <strong>public function </strong>getUrl(){<br>        <strong>if</strong>(<strong>isset</strong>($_GET[&#39;url&#39;])){<br>            $url = rtrim($_GET[&#39;url&#39;], &#39;/&#39;);<br>            $url = filter_var($url, <em>FILTER_SANITIZE_URL</em>);<br>            $url = explode(&#39;/&#39;, $url);<br>            <strong>return </strong>$url;<br>            }<br>    }<br>}</pre><ul><li>The getUrl() method is checking to see if the url parameter ($_GET[‘url’]) we attached in the .htaccess file isset. So this returns what’s in the url.</li><li>The $_GET[‘url’] is then passed to rtrim() PHP built-in function to remove characters from the right side of a string. To make sure we don’t have unwanted characters to the right of the url. And its return to $url.</li><li>Lets now filter the value in the $url with <em>FILTER_SANITIZE_URL to remove </em>all illegal URL characters from a string.</li><li>Finally, lets split the string into an array of values and return the array.</li><li>Back in the constructor, we check the content in the url from getUrl() method.</li><li>The first index of the array $url[0], we will check for the controller, if the controller exist in the controller directory, then lets set that to the property $currentController else the $currentController is set to a default controller ‘Pages’, we must then unset the index $url[0].</li><li>With the controller set, let us now check for the method with the second index $url[1] of the $url. If the method exist in the $currentController, then lets set it to the property $currentMethod. Otherwise the property $currentMethod is set to a default method ‘Index’.</li><li>A new array of parameter $params is created with whatever is left in the $url array.</li><li>Now lets make a callback to the controller and method and pass the $param to it.</li></ul><h3>Next The Controller Class</h3><pre><strong>&lt;?php<br></strong><em>/**<br> * </em><strong>app/libraries/Controller.php<br> </strong><em>* Controller Class Library <br> * Loads the models and views<br> */<br></em><strong>class </strong>Controller {<br><br>    //Load Model<br><br>    <strong>public function </strong>model($model){<br>        // Require Model file<br>        <strong>require_once </strong>&#39;./app/models/&#39;. $model . &#39;.php&#39;;<br><br>        //Instantiate the model<br><br>        <strong>return new </strong>$model();<br>    }<br><br>    // Load View<br><br>    <strong>public function </strong>view($view, $data=[]){<br>        // Check for the view file<br>        <strong>if</strong>(file_exists(&#39;./app/views/&#39;.$view.&#39;.php&#39;)){<br>            <strong>require_once </strong>&#39;./app/views/&#39;.$view.&#39;.php&#39;;<br>        } <strong>else</strong>{<br>            // View does not exist<br>            <strong>die</strong>(&#39;View does not exist&#39;);<br>        }<br>    }<br><br>}</pre><ul><li>The Controller class is responsible for loading both the model and view for the controller.</li><li>Every Controller will inherit from this class.</li><li>The view method takes in two argument, the view itself and the data to be passed to the view.</li></ul><p>Note: We do not need the Database class in our app, go ahead and skip that part.</p><h3>Next, Create the “Pages Controller”</h3><p>The pages controller is the default controller, and we will be defining the index method for the home page.</p><pre><strong>&lt;?php<br>// app/controllers/Pages.php</strong></pre><pre><strong>class </strong>Pages <strong>extends </strong>Controller {    <br>    <strong>public function </strong>index(){<br>            $data = [<br>                &#39;title&#39; =&gt; &#39;TweetMini&#39;<br>            ];<br>            $this-&gt;view(&#39;pages/index&#39;, $data);<br>        }<strong>else</strong>{<br>            redirect(&#39;users/index&#39;);<br>        }<br>    }<br>  }</pre><ul><li>Let’s go ahead type <a href="http://localhost/tweetmini/">http://localhost/tweetmini/</a> in the URL bar and test the app up to this stage.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*eOO33oq8ypVRIrykuDyuUw.jpeg" /></figure><p>This is the result we get and this is because we have not created the view for the index() method in the Pages controller.</p><p>Let’s go into the app/view directory, create another directory <strong>pages</strong> and create the view <strong>index.php</strong> for the index() method.</p><p>I am going to be using bootstrap 4 for the UI. You can head over to <a href="http://getbootstrap.com/docs/4.0/examples/">bootstrap</a> example page and grab some template.</p><p>Let’s also test passing data to the view.</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot;<br>          content=&quot;width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css&quot; integrity=&quot;sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;title&gt;TweetMini&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;nav class=&quot;navbar navbar-expand-md navbar-dark bg-dark mb-3&quot;&gt;<br>    &lt;a class=&quot;navbar-brand&quot; href=&quot;#&quot;&gt;TweetMini&lt;/a&gt;<br>    &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarsExampleDefault&quot; aria-controls=&quot;navbarsExampleDefault&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt;<br>        &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;<br>    &lt;/button&gt;<br><br>    &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarsExampleDefault&quot;&gt;<br>        &lt;ul class=&quot;navbar-nav mr-auto&quot;&gt;<br>            &lt;li class=&quot;nav-item active&quot;&gt;<br>                &lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Home &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/a&gt;<br>            &lt;/li&gt;<br>            &lt;li class=&quot;nav-item&quot;&gt;<br>                &lt;a class=&quot;nav-link&quot; href=&quot;#&quot;&gt;Link&lt;/a&gt;<br>            &lt;/li&gt;<br>            &lt;li class=&quot;nav-item&quot;&gt;<br>                &lt;a class=&quot;nav-link disabled&quot; href=&quot;#&quot;&gt;Disabled&lt;/a&gt;<br>            &lt;/li&gt;<br>        &lt;/ul&gt;<br>    &lt;/div&gt;<br>&lt;/nav&gt;<br>&lt;h2&gt;<strong>&lt;?php echo </strong>$data[&#39;title&#39;]; <strong>?&gt;</strong>&lt;/h2&gt;<br><br><br><br>&lt;script src=&quot;https://code.jquery.com/jquery-3.2.1.slim.min.js&quot; integrity=&quot;sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js&quot; integrity=&quot;sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js&quot; integrity=&quot;sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*u1oY8sM2XrK7Y1z5Kv4ygQ.jpeg" /></figure><p>Yay!!, congrats on loading your first view. But we have to do this properly, lets create another directory <strong>includes</strong> in app/views, to hold the header, navbar and footer file. Then we can include these files when creating any view.</p><p><strong>app/views/includes/header.php</strong></p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot;<br>          content=&quot;width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0&quot;&gt;<br>    &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;ie=edge&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css&quot; integrity=&quot;sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb&quot; crossorigin=&quot;anonymous&quot;&gt;<br>    &lt;title&gt;<strong>&lt;?php echo </strong><em>SITENAME</em>; <strong>?&gt;</strong>&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;</pre><p><strong>app/views/includes/navbar.php</strong></p><pre>&lt;nav class=&quot;navbar navbar-expand-md navbar-dark bg-dark&quot;&gt;<br>    &lt;a class=&quot;navbar-brand&quot; href=&quot;<strong>&lt;?php echo </strong><em>URLROOT</em>; <strong>?&gt;</strong>&quot;&gt;<strong>&lt;?php echo </strong><em>SITENAME</em>; <strong>?&gt;</strong>&lt;/a&gt;<br>    &lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarsExampleDefault&quot; aria-controls=&quot;navbarsExampleDefault&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt;<br>        &lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;<br>    &lt;/button&gt;<br><br>    &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarsExampleDefault&quot;&gt;<br>        &lt;ul class=&quot;navbar-nav mr-auto&quot;&gt;<br>            &lt;li class=&quot;nav-item active&quot;&gt;<br>                &lt;a class=&quot;nav-link&quot; href=&quot;<strong>&lt;?php echo </strong><em>URLROOT</em>; <strong>?&gt;</strong>&quot;&gt;Home &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/a&gt;<br>            &lt;/li&gt;<br>        &lt;/ul&gt;<br>        &lt;ul class=&quot;navbar-nav ml-auto&quot;&gt;<br>            &lt;li class=&quot;nav-item&quot;&gt;<br>                &lt;a class=&quot;nav-link&quot; href=&quot;<strong>&lt;?php echo </strong><em>URLROOT</em>; <strong>?&gt;</strong>/users/logout&quot;&gt;Logout&lt;/a&gt;<br>            &lt;/li&gt;<br>        &lt;/ul&gt;<br>    &lt;/div&gt;<br>&lt;/nav&gt;</pre><p><strong>app/views/includes/footer.php</strong></p><pre>&lt;script src=&quot;https://code.jquery.com/jquery-3.2.1.slim.min.js&quot; integrity=&quot;sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js&quot; integrity=&quot;sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;script src=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js&quot; integrity=&quot;sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Now, the <strong>pages/index.php</strong> view will change to this.</p><p>We’ll also have to include the path to the required files and that’s where the APPROOT constant comes in.</p><pre><strong>// app/views/pages/index.php</strong></pre><pre><strong>&lt;?php require </strong><em>APPROOT </em>. &#39;/views/includes/header.php&#39;; <strong>?&gt;<br>&lt;?php require </strong><em>APPROOT </em>. &#39;/views/includes/navbar.php&#39;; <strong>?&gt;<br></strong>&lt;div class=&quot;container&quot;&gt;<br>    &lt;div class=&quot;jumbotron jumbotron-flud text-center&quot;&gt;<br>        &lt;div class=&quot;container&quot;&gt;<br>            &lt;h1 class=&quot;display-3&quot;&gt;<strong>&lt;?php echo </strong>$data[&#39;title&#39;]; <strong>?&gt;</strong>&lt;/h1&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;<br><strong>&lt;?php require </strong><em>APPROOT </em>. &#39;/views/includes/footer.php&#39;; <strong>?&gt;</strong></pre><p>With our view loading up, lets now configuring our Twitter Api and create our app.</p><p>We will be using the <a href="https://github.com/abraham/twitteroauth"><strong>PHP Twitter OAuth REST API</strong></a> from TwitterOAuth, you can clone or download it from <a href="https://github.com/abraham/twitteroauth"><strong>github</strong></a><strong>. </strong>Go ahead, download and extract it. We will need autoload.php file and the src directory then all of them into the libraries directory. Here’s a look at our file directory now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*1uLvlH_mOpZ57RQqBIYRiw.jpeg" /></figure><p>As you can see, the extracted files autoload.php and the src directory are all inside <strong>app/libraries</strong> directory.</p><p>Let’s now require the autoload.php in the app/bootstrap. php file.</p><pre><strong>&lt;?php<br>// app/bootstrap.php</strong></pre><pre>// Load Config file<br><strong>require_once </strong>&#39;config/config.php&#39;;<br><strong>require_once </strong>&#39;helpers/functions.php&#39;;<br><strong>require_once </strong>&#39;libraries/autoload.php&#39;;</pre><pre><strong>use </strong>Abraham\TwitterOAuth\TwitterOAuth;</pre><pre>// Load Core classes<br><strong>require_once </strong>&#39;libraries/Core.php&#39;;<br><strong>require_once </strong>&#39;libraries/Database.php&#39;;<br><strong>require_once </strong>&#39;libraries/Controller.php&#39;;</pre><h3>Register a Twitter Application</h3><p>Our task in this example is to communicate with Twitter API and make get and post requests.</p><p>To do this, we will have to create/register a Twitter application. The reason for doing this is to get access to some important information which we will when making request. The information we will need to get from the Twitter application are:</p><ul><li>Client ID</li><li>Client Secret.</li></ul><p>Go to <a href="https://apps.twitter.com/">https://apps.twitter.com/</a>, and create a new application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*TTl50WCtKS1ItJkmP0Th5g.jpeg" /></figure><ul><li>Application Name: Name of your choice</li><li>Description: A simple description</li><li>Website URL: <a href="http://localhost:3000/">http://localhost/</a>tweetmini</li><li>Callback URL: <a href="http://localhost:3000/">http://localhost</a>/tweetmini/callback.php</li></ul><p>Note: You can put your site name in the Website URL, the Callback URL doesn’t really matter because when making the request we are going to specify a callback, so it can be set to h<a href="http://localhost:3000/">ttp://localhost</a>/tweetmini/callback.php.</p><p>After creating the twitter application, click on the Keys and Access Tokens tab to reveal the Consumer Key (API Key) and Consumer Secret (API Secret).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*xhhNXN1_p9pK8Ebp67zLdw.jpeg" /></figure><p>Let’s go into the config.php file and include the consumer key and consumer secret. We also have to define a callback url to which authorization data will be returned to.</p><pre>// <strong>app/config/config.php</strong></pre><pre>define(&#39;CONSUMER_KEY&#39;, &#39;YOUR_CONSUMER_KEY&#39;);<br>define(&#39;CONSUMER_SECRET&#39;, &#39;YOUR_CONSUMER_SECRET&#39;);<br>define(&#39;OAUTH_CALLBACK&#39;, &#39;http://localhost/tweetmini/pages/callback&#39;);</pre><p>For user’s to login we need to generate the <strong>url</strong> for authorization and then fetching the user basic info when once u get back from <strong>twitter.</strong></p><p>Let’s go into the <strong>index()</strong> method in the ‘Pages’ controller and update it.</p><pre><strong>// app/controllers/Pages.php</strong></pre><pre><strong>public function </strong>index(){<br><br>    <strong>if</strong>(!<strong>isset</strong>($_SESSION[&#39;access_token&#39;])) {<br>        $connection = <strong>new </strong>\Abraham\TwitterOAuth\TwitterOAuth(<em>CONSUMER_KEY</em>, <em>CONSUMER_SECRET</em>);<br>        $request_token = $connection-&gt;oauth(&#39;oauth/request_token&#39;, <strong>array</strong>(&#39;oauth_callback&#39; =&gt; <em>OAUTH_CALLBACK</em>));<br><br>        $_SESSION[&#39;oauth_token&#39;] = $request_token[&#39;oauth_token&#39;];<br>        $_SESSION[&#39;oauth_token_secret&#39;] = $request_token[&#39;oauth_token_secret&#39;];<br><br>       $url = $connection-&gt;url(https://medium.com/&#39;oauth/authorize&#39;,%20%20%20%20%3Cstrong%3Earray%3C/strong%3E(&#39;oauth_token&#39;%20=&gt;%20$request_token[&#39;oauth_token&#39;]));<br>        $data = [<br>            &#39;title&#39; =&gt; &#39;TweetMini&#39;,<br>            &#39;url&#39; =&gt; $url<br>        ];<br>        $this-&gt;view(&#39;pages/index&#39;, $data);<br>    } <strong>else</strong>{<br>        redirect(&#39;users/index&#39;);<br>    }<br>}</pre><ul><li>Here we are trying to verify if $_SESSION[‘access_token’] is set, if it’s not set then we proceed to make a new connection to twitter.</li><li>Let’s create a new connection by instantiating TwitterOAuth() class with <em>CONSUMER_KEY</em>, <em>CONSUMER_SECRET</em> as argument. This connection is stored in the $connection variable.</li><li>With the new connection instance, we now make a call to oauth() method with ‘oauth/request_token’ and callback url as arguments.</li><li>We get an array of values as the result which is stored in the $request_token variable.</li><li>Now we can access oauth_token and oauth_token_secret values. We then save these values in session variables $_SESSION[‘oauth_token’], $_SESSION[‘oauth_token_secret’] respectively.</li><li>Now we can make a request for an authorization url, this authorization url is stored in the $url variable which we pass to the view.</li><li>But if $_SESSION[‘access_token’] is set then let us redirect the user to user/index which we have not created yet.</li></ul><p>In the index view, we will add an anchor tag in the jumbotron and pass in the authorization url as the link in the href attribute.</p><pre>&lt;div class=&quot;container&quot;&gt;<br> &lt;div class=&quot;jumbotron jumbotron-flud text-center&quot;&gt;<br>   &lt;div class=&quot;container&quot;&gt;<br>     &lt;h1 class=&quot;display-3&quot;&gt;<strong>&lt;?php echo </strong>$data[&#39;title&#39;]; <strong>?&gt;</strong>&lt;/h1&gt;<br>&lt;a href=&quot;<strong>&lt;?php echo </strong>$data[&#39;url&#39;]; <strong>?&gt;</strong>&quot; class=&quot;btn btn-dark&quot;&gt;Login&lt;/a&gt;<br>   &lt;/div&gt;<br> &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Now when a user visits your app, clicks on login it takes the user to a twitter page where they will give your app the authority to access their information.</p><p>Twitter then sends back a response to the callback url we specified in the config.php file. The response is returned in the url like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*y-kEMUQwI3ew-Cso9gfweA.jpeg" /></figure><p>Let’s now add another method callback() to the pages controller that will handle the response we get and then redirect the user to users/index controller which we will create in a minute.</p><pre><strong>public function </strong>callback(){<br>    <strong>if</strong>(<strong>isset</strong>($_GET[&#39;oauth_token&#39;], $_GET[&#39;oauth_verifier&#39;]) &amp;&amp; $_GET[&#39;oauth_token&#39;] == $_SESSION[&#39;oauth_token&#39;]){<br>        $request_token = [];<br>        $request_token[&#39;oauth_token&#39;] = $_SESSION[&#39;oauth_token&#39;];<br>        $request_token[&#39;oauth_token_secret&#39;] = $_SESSION[&#39;oauth_token_secret&#39;];<br>        $connection = <strong>new </strong>\Abraham\TwitterOAuth\TwitterOAuth(<em>CONSUMER_KEY</em>, <em>CONSUMER_SECRET</em>, $request_token[&#39;oauth_token&#39;], $request_token[&#39;oauth_token_secret&#39;]);<br>        $access_token = $connection-&gt;oauth(&quot;oauth/access_token&quot;, <strong>array</strong>(&quot;oauth_verifier&quot; =&gt; $_GET[&#39;oauth_verifier&#39;]));<br><br>        $_SESSION[&#39;access_token&#39;] = $access_token;<br>        redirect(&#39;users/index&#39;);<br>        <br>    }<br>}</pre><h3><strong>Create The Users Controller</strong></h3><p>In the users controller, we are going define two methods, index() to fetch users basic details and tweets. And logout to basically destroy user session and log the user off.</p><pre><strong>&lt;?php<br></strong><em>/**<br> * </em><strong><em>app/controllers/Users.php</em></strong><em><br> */<br><br></em><strong>class </strong>Users <strong>extends </strong>Controller{<br><br>    <strong>public function </strong>index(){<br>        <strong>if</strong>(<strong>isset</strong>($_SESSION[&#39;access_token&#39;])){<br>            $access_token = $_SESSION[&#39;access_token&#39;];<br>            $connection = <strong>new </strong>\Abraham\TwitterOAuth\TwitterOAuth(<em>CONSUMER_KEY</em>, <em>CONSUMER_SECRET</em>, $access_token[&#39;oauth_token&#39;], $access_token[&#39;oauth_token_secret&#39;]);<br><br>            $user = $connection-&gt;get(&quot;account/verify_credentials&quot;);<br><br>            $tweets = $connection-&gt;get(&#39;statuses/home_timeline&#39;, [&#39;count&#39; =&gt; 200]);<br><br>            $data = [<br>                &#39;tweets&#39; =&gt; $tweets,<br>                &#39;user&#39; =&gt; $user<br>            ];<br>            $this-&gt;view(&#39;users/index&#39;, $data);<br>        }<br>    }<br>    <br>    <strong>public function </strong>logout(){<br>        //Remove user data from session<br>        <strong>unset</strong>($_SESSION[&#39;access_token&#39;]);<br><br>        //Destroy all session data<br>        session_destroy();<br><br>        //Redirect to the homepage<br>        redirect(&quot;index&quot;);<br>    }<br>}</pre><ul><li>In the index() method, a new connection is made and make a request to get the user’s basic info and user’s timeline.</li><li>To get the user’s basic information, we are making a get request to ‘account/verify_credentials’. The response is stored in $user variable. Do a print_r($user) to see all the information you can get for the user.</li><li>To get the user’s timeline, we are also making a get request to ‘statuses/home_timeline’, a number of parameters can be passed along with the request eg. ‘count’ =&gt; 200 which specifies the number of records to retrieve.</li><li>We can then pass all that information to the view.</li></ul><p><strong>The view for users/index controller.</strong></p><pre><strong>&lt;?php require </strong><em>APPROOT </em>. &#39;/views/includes/header.php&#39;; <strong>?&gt;<br>&lt;?php require </strong><em>APPROOT </em>. &#39;/views/includes/navbar.php&#39;; <strong>?&gt;<br>    </strong>&lt;div class=&quot;container&quot;&gt;<br>        &lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;col-sm-4&quot;&gt;<br>                &lt;div class=&quot;card-body&quot;&gt;<br>                    &lt;h4 class=&quot;card-title&quot;&gt;<strong>&lt;?php echo </strong>$data[&#39;user&#39;]-&gt;name; <strong>?&gt;</strong>&lt;/h4&gt;<br>                    &lt;button class=&quot;btn btn-default&quot;&gt;Following &lt;span class=&quot;badge badge-pill badge-success&quot;&gt;<strong>&lt;?php echo </strong>$data[&#39;user&#39;]-&gt;friends_count; <strong>?&gt;</strong>&lt;/span&gt;&lt;/button&gt;<br>                    &lt;button class=&quot;btn btn-default&quot;&gt;Followers &lt;span class=&quot;badge badge-pill badge-success&quot;&gt;<strong>&lt;?php echo </strong>$data[&#39;user&#39;]-&gt;followers_count; <strong>?&gt;</strong>&lt;/span&gt;&lt;/button&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>            &lt;div class=&quot;col-sm-8&quot;&gt;<br>                &lt;div class=&quot;row&quot;&gt;<br>                    &lt;div class=&quot;col&quot;&gt;<br>                        &lt;h2&gt;Lastest Tweet&lt;/h2&gt;<br>                        <strong>&lt;?php foreach </strong>($data[&#39;tweets&#39;] <strong>as </strong>$tweet) : <strong>?&gt;<br>                            </strong>&lt;div class=&quot;card mb-1&quot;&gt;<br>                                &lt;div class=&quot;card-body&quot;&gt;<br>                                    <strong>&lt;?php echo </strong>$tweet-&gt;text; <strong>?&gt;<br><br>                                    </strong>&lt;a href=&quot;<strong>&lt;?php if</strong>(<strong>isset</strong>($tweet-&gt;entities-&gt;urls[0]-&gt;url)){<strong>echo </strong>$tweet-&gt;entities-&gt;urls[0]-&gt;url;} <strong>?&gt;</strong>&quot;&gt;<strong>&lt;?php if</strong>(<strong>isset</strong>($tweet-&gt;entities-&gt;urls[0]-&gt;url)){<strong>echo </strong>$tweet-&gt;entities-&gt;urls[0]-&gt;url;} <strong>?&gt;</strong>&lt;/a&gt;<br>                                &lt;/div&gt;<br>                            &lt;/div&gt;<br>                            <strong>&lt;?php endforeach</strong>; <strong>?&gt;<br>                    </strong>&lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br><strong>&lt;?php require </strong><em>APPROOT</em>. &#39;/views/includes/footer.php&#39;; <strong>?&gt;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T0dUMXY_IirvGO2InHiWew.jpeg" /></figure><p>Viola! Our app works perfectly well! You can play with the code <a href="https://github.com/japhyamg/tweetmini">HERE</a>. There is also a live version <a href="http://jaelinc.xyz/tweetmini/">HERE</a>.</p><h3>Conclusion</h3><p>We’ve built our app with Twitter API from <a href="https://github.com/abraham/twitteroauth"><strong>PHP Twitter OAuth REST API</strong></a>, making a request to Twitter’s API and getting a response. Feel free to add any other feature you want your app to have, here we only pull the user’s timeline. The MVC framework can also be a based to create more awesome apps, as it’s easy to understand.</p><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f2765a91d77" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>