Today I learned about how to separate PHP logic from template.
Important, must read
- As I mentioned in my last post, I explained how to add functions and filter them in the code. However, to separate the logic from the template, we need to create two files:
index.view.php
for the template andindex.php
for the logic.
Diving in code
In a fresh vs code project (version 1.90 at the time of working), we need two different files to easily learn the working of code.
A template file which contains PHP code that contains a condition inside it in the body tag of HTML
Second file is to perform PHP logics in it. It contains array of books and functions etc.
On VS Code Side
- Firstly create a file named
index.view.php
that have HTML5 basic code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>You have read in dark mode </h1>
</body>
</html>
CSS on body tag
- Also in this file the styling of
body
tag is present and it's code is as follows.
<style>
body {
display: grid;
place-items: center;
font-family: sans-serif;
height: 100px;
margin: 20px;
}
</style>
This takes the data present in body in the centre of output screen by giving height, margin and font-family.
PHP condition inside this file
This condition is used to show an unordered list of filtered books at output screen.
<!-- Display filtered books -->
<ul>
<?php foreach ($filteredBooks as $book) : ?>
<li><?= $book['name']; ?> - by <?= $book['author'] ?></li>
<?php endforeach; ?>
</ul>
Second file as PHP logic
Second file that is used for logic is named as index.php
which contains function to filter books by author name and an associate array of books.
<?php
function filterBooksByAuthor($books, $author) {
$filteredBooks = array_filter($books, function($book) use ($author) {
return $book['author'] == $author;
});
return $filteredBooks;
}
$books = [
['name' => 'Web', 'author' => 'Philip K. Dick', 'purchaseUrl' => 'http://example.com'],
['name' => 'OOP', 'author' => 'Andy Weir', 'purchaseUrl' => 'http://example.com'],
['name' => 'Database', 'author' => 'Jeffery', 'purchaseUrl' => 'http://example.com']
];
$filteredBooks = filterBooksByAuthor($books, 'Andy Weir');
After adding this, when we start to debug and run the code a blank screen is shown. To resolve this issue add template file index.view.php
in this at the end of above code.
require"Index.view.php";
Now the output will show.
I hope that you have clearly understand everything
Top comments (0)