ПОЛИТИКА ЗА ПОВЕРИТЕЛНОСТ И ЗАЩИТА НА ЛИЧНИ ДАННИ

PHP App with Layered Archtiecture - Step 1

The goal of layered software architectural style is to divide the tasks for visualisation, data retrieving and handling. How to make simple PHP application with layered architecture? Here is one solution.

  • Create Database
    1. Create database with name blog
    2. Create table named post
    3. Create two records in table post for tests
  • Create new project
    1. Create new project with NetBeans or VSC or other PHP editor with name blog
    2. Create folder structure of the project
  • Create database class
    1. This class establish database connection
    2. The class use real database configuration settings as host, user, password and database name
  • Create service class
    1. This class use database connection
    2. The class has method for reading of one record by concrete ID, this method use FetchAll
  • Create code in index.php for testings
    1. Include the class files
    2. Instantiate new service
    3. Use this service variable for showing the record for concrete ID
  • Change service class method to get class object
    1. Create empty class Post
    2. Use FetchObject
    3. The big idea is ...

Create database

  1. Create database with name blog
  2. Create table named post
  3. Create two records in table post for tests
						
DROP DATABASE IF EXISTS `blog`;
CREATE DATABASE IF NOT EXISTS `blog` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `blog`;

DROP TABLE IF EXISTS `post`;
CREATE TABLE IF NOT EXISTS `post` (
  `postID` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `author` varchar(255) NOT NULL,
  `content` text NOT NULL,
  `img` varchar(255) NOT NULL,
  `category` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`postID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

INSERT INTO `post` (`postID`, `title`, `author`, `content`, `img`, `category`) VALUES
	(1, 'First Post', 'Author', 'lorem ipsum...', '', 'math'),
	(2, 'Second Post', 'Author', 'text, text, text', '', 'math');							
						

Create new project and folder structure

  1. Create new project with NetBeans or VSC or other PHP editor with name blog
  2. Create folder structure of the project
						
blog
|_____config
|     |_____Database.php
|
|_____service
|     |_____PostService.php 
|
|___________index.php             
							
						

Create database class

  1. This class establish database connection
  2. The class use real database configuration settings as host, user, password and database name
<?php
	class Database {	
	private $connection = '';
	private $host = "localhost";
	private $username = "root";
	private $password = "";
	private $database = "blog";
	//private $charset = 'utf8mb4';
	public $opt = [
		PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
		PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
		PDO::ATTR_EMULATE_PREPARES => false,
	];

	function __construct() {
		$this->database_connection();
	}

	function database_connection() {
		$this->connection = new \PDO("mysql:host=" . $this->host . ";dbname=" 
			. $this->database, $this->username, $this->password, $this->opt);
		$this->connection->exec("set names utf8");
	}
	function getConnection() {
		return $this->connection;
	}
}				
?>		

Create service class

  1. This class use database connection
  2. The class has method for reading of one record by concrete ID, this method use FetchAll
class PostService {
	private $conn;
	private $database;

	public function __construct(Database $database) {
		$this->database=$database;
		$this->conn = $database->getConnection();
	}
	
	public function readPost($id) {
		$query = "SELECT * FROM post WHERE postID=?";
		$form_data = [$id];
		$statement = $this->conn->prepare($query);
		$data = array();
		if ($statement->execute($form_data)) {
			
			foreach ($statement->fetchAll() as $row) {
				$postID = $row['postID'];				
				$data[$postID]['title'] = $row['title'];
				$data[$postID]['content'] = $row['content'];			
			}
	
		}
		return $data;
	}
}
	

Create code in index.php for testings

  1. Include the class files
  2. Instantiate new service
  3. Use this service variable for showing the record for concrete ID
		
		<?php
		include 'config/Database.php';
		include 'service/PostService.php';
		$db= new Database();
		$s= new PostService($db);
		$id=1;
		print_r($s->readPost($id));		
		?>
    
	

This is the result:

Array ( [1] => Array ( [title] => First Post [content] => lorem ipsum... ) )

Change service class method to get class object

  1. Create empty class Post
  2. Use FetchObject
  3. The big idea is: If service can return object with field title, author, content, etc. the same as the filed of every record for post, it's easy to create independent code for Creating, Reading, Editing and Deleting [CRUD] of every post.
class Post{};
class PostService {
	private $conn;
	private $database;

	public function __construct(Database $database) {
		$this->database=$database;
		$this->conn = $database->getConnection();
	}
	
	public function readPost($id) {
		$query = "SELECT * FROM post WHERE postID=?";
		$form_data = [$id];
		$statement = $this->conn->prepare($query);
		$data = array();
		if ($statement->execute($form_data)) {
			
//			foreach ($statement->fetchAll() as $row) {
//				$postID = $row['postID'];				
//				$data[$postID]['title'] = $row['title'];
//				$data[$postID]['content'] = $row['content'];			
//			}
			$data=$statement->fetchObject(Post::class);
	
		}
		return $data;
	}
}
	

The result with using object:

Post Object ( [postID] => 1 [title] => First Post [author] => Author [content] => lorem ipsum... [img] => [category] => math )