Coding a PHP 7 Framework #1 - Code Workshop

In part 1 of Coding a PHP Framework, we detail environment requirements, coding style and basic setup.



Coding a PHP 7 Framework #1 - Code Workshop

1st August 2018 in   PHP Tutorials by Elliott Barratt

In this series of articles, we'll walk through the coding of a PHP micro-framework. It is assumed you are fairly familiar with PHP and coding / developing in general, however we'll try to explain each step so that a novice could follow.

You can view the finished framework at any time by visiting the GitHub repo at https://github.com/erbarratt/lectric.

If you need more space to see the code, click "Hide Sidebar >" above the Article Categories box to the right ->

Requirements

Before we start coding anything, a few things need to be stated and sorted out:

  • The framework we'll be creating will utilise features only found in PHP version 7.1 and above.
  • We'll be using a LAMP stack, but you can transpose / modify to suite your development environment (WAMP, nginx etc).
    • Linux (CentOS)
    • Apache 2+
      • Needs mod_rewrite and PDO extensions enabled.
    • MariaDB or MySQL
    • PHP (aforementioned 7.1)

And that's about it. If you're unsure, then you can opt to use hosting such as https://www.one.com and purchase a cheap ".website" domain name to follow along.

Editor

Notepad++, with the NppFTP plugin is recommended for following this tutorial.

Directory Tree

Go ahead and in your root directory add the following files and folders:

  • do/
  • engine/
    • app_config.php
    • config.php
    • init.php
  • library/
    • Lectric/
      • lecPDO.class.php
      • controlAction.class.php
      • controller.class.php
      • doAction.class.php
      • doResponse.class.php
      • view.class.php
  • view/
    • public/
      • render.php
      • css/
        • style.css
      • img/
      • js/
      • template/
        • common/
          • header.php
          • content.php
          • footer.php
        • views/
          • index.php
  • index.php
  • .htaccess

Make sure to set the appropriate permissions on the folders (I recommend 711 recursively, only on folders, 644 for php files).

File encoding

Ensure all your PHP files are encoded as UTF8. Most code editors will display this information. For example, in notepad++, the encoding is displayed in the status bar at the bottom right of the window, and you can set the encoding to UTF8 from the "Encoding" menu.

Database

Run the SQL statement below to create some example tables and insert some test data for use later in the development.

CREATE TABLE IF NOT EXISTS `public_directories` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8_bin DEFAULT NULL,
  `live` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

INSERT INTO `public_directories` (`id`, `name`, `live`) VALUES
	(1, 'root', 1);

	CREATE TABLE IF NOT EXISTS `public_views` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `pageheading` varchar(250) COLLATE utf8_bin DEFAULT NULL,
  `pagesubheading` varchar(250) COLLATE utf8_bin DEFAULT NULL,
  `navheading` varchar(250) COLLATE utf8_bin DEFAULT NULL,
  `url` varchar(250) COLLATE utf8_bin DEFAULT NULL,
  `html` mediumtext COLLATE utf8_bin,
  `althtml` mediumtext COLLATE utf8_bin,
  `metatitle` varchar(250) COLLATE utf8_bin DEFAULT NULL,
  `metadescription` varchar(250) COLLATE utf8_bin DEFAULT NULL,
  `metakeywords` varchar(250) COLLATE utf8_bin DEFAULT NULL,
  `directory` tinyint(1) NOT NULL DEFAULT '1',
  `live` tinyint(1) NOT NULL DEFAULT '0',
  `sidebar` tinyint(1) NOT NULL DEFAULT '0',
  `js` varchar(255) COLLATE utf8_bin DEFAULT NULL,
  `filename` varchar(250) COLLATE utf8_bin DEFAULT NULL,
  `ext` varchar(50) COLLATE utf8_bin DEFAULT NULL,
  `permission` varchar(50) COLLATE utf8_bin DEFAULT 'none',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;


INSERT INTO `public_views` (`id`, `pageheading`, `pagesubheading`, `navheading`, `url`, `html`, `althtml`, `metatitle`, `metadescription`, `metakeywords`, `directory`, `live`, `sidebar`, `js`, `filename`, `ext`, `permission`) VALUES
	(1, 'Error', 'Page Not Found', 'Error', 'error', '', NULL, 'Error', '', '', 1, 1, 0, '', '', '', 'none'),
	(2, 'Lectric', 'Lectric', 'Lectric', 'index', 'Congrats, dude! If you\'re seeing this, it means the installation was almost a success.', '', 'Lectric Framework', 'Homepage of the Lectric Framework default view directory', '', 1, 1, 0, 'js_home.php', 'favicon.png', '', 'none');

It's important that all our table encoding is UTF8_bin, which will make our lives easier later.

CARVin it up!

Let's look at the definition of a framework:

"A software framework provides a standard way to build and deploy applications."

In the context of web applications, the basic pricipal is that most web apps are tools for viewing something, performing an action or generating a none-view response. Exactly what a framework does, generate a view, response or run an action is determined by the url. Thus, the framework we'll create is tentaively called a C-ARV framework, standing for Controller -> Action / Response / View. 

Unlike MVC or other design patterns, the framework we'll create will lean into being web-oriented (not to say we won't try to keep separation of concerns!) and use the action/response/view methodology to route logic via a simple controller whose job it is to parse a URL.

Bootstrap

Ok, with the prep out of the way, let's get creating our first few files. We'll implement a very simple bootstrap whose job it is to send all requests through one file, being /index.php, who will in turn start the application by inclusion of other files. This allows us to implement a rudimentary level of security within our directory structure.

.htaccess

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule ^(.*)$ index.php [PT,L]

</IfModule>

The htaccess file only has a few instructions. Firstly, we check to see if a specific file is being requested (for example, an image we want to use on a webpage), if not then the request is forwarded to /index.php. This will only work if mod_rewrite is on and working.

/index.php

<?php

/**
* call up the bootstrap initialiser 
*/
if (file_exists(__DIR__.'/engine/init.php')) {
	require(__DIR__.'/engine/init.php');
} else {
	die('Init file not found');
}

The index file's job is to require the /engine/init.php file or stop execution, and that's it!

/engine/init.php

<?php

	/**
	* set up the system parameter via config
	*/
		if (file_exists(__DIR__.'/config.php')) {
			require(__DIR__.'/config.php');
		} else {
			die('<p>Config file not found at <doc_root>/engine/config.php</p>');
		}

	/*
	* controller instantiate
	*/
		$lecController = new \Lectric\controller($lecDBH); 

init.php's job is to go and find the framework configuration file /engine/config.php and then instantiate the controller class. For now, don't worry about what the controller is / does, or what the argument passed to it $lecDBH is, we'll get to that in due course.

And that's the bootstrap done! Now we have the basic setup to start into the meat of the framework in the next article, filling the /engine/config.php file with various settings and logic to allow our framework to function correctly.

Continue to Part 2 by clicking here.




Hide Sidebar >



Archive



Search


Hide Sidebar >


This website uses cookies. Privacy Policy