Samouczek dotyczący frameworka PHP MVC
⚡ Inteligentne podsumowanie
PHP MVC Framework design separates application data and business logic from presentation, using Models, Views, and Controllers. CodeIgniter makes this pattern practical, letting PHP developers build secure, maintainable web applications faster.
Co to jest framework PHP MVC?
PHP MVC to wzorzec projektowania aplikacji, który oddziela dane aplikacji i logikę biznesową (model) od prezentacji (widoku). MVC oznacza model, widok i kontroler.
Kontroler pośredniczy pomiędzy modelami i widokami.
Pomyśl o wzorcu projektowym MVC jak o samochodzie i kierowcy.
The car has the windscreens (view) which the driver (controller) uses to monitor traffic ahead, then speed up or brake (model) depending on what he sees ahead.
Next, let’s see why a framework built on this pattern is worth using.
Dlaczego warto używać PHP MVC Framework?
PHP MVC frameworks simplify working with complex technologies by:
- Ukrywanie wszystkich skomplikowanych szczegółów implementacji
- Providing standard methods that we can use to build our applications
- Increasing developer productivity, because base implementations of activities such as connecting to the database and sanitizing user input are already partially implemented
- Encouraging adherence to professional coding standards
Wzorzec projektowy PHP MVC
Omówmy teraz pokrótce każdy komponent wzorca projektowego MVC.
Model – ta część dotyczy logiki biznesowej i danych aplikacji. Może służyć do przeprowadzania walidacji danych, przetwarzania danych i ich przechowywania. Dane mogą pochodzić z;
- płaski plik
- baza danych
- Dokument XML
- Inne ważne źródła danych.
kontroler – this is the part that deals with the user’s requests for resources from the server.
As an example, when the user requests the URL …/index.php?products=lista, the controller will load the products model to retrieve the products data, then output the results in the list view.
Krótko mówiąc, kontroler łączy ze sobą modele i widoki w zależności od żądanych zasobów.
odwiedzajacy – this part deals with presenting the data to the user. This is usually in the form of HTML pages.
Rodzaje frameworka PHP MVC
Wybór najlepszego frameworka PHP jest wyzwaniem.
Nie musisz pisać własnego frameworka, aby skorzystać z zalet MVC.
Powinieneś próbować stworzyć własny projekt aplikacji związany z MVC, aby zrozumieć, jak działają frameworki MVC.
Kiedy już poczujesz się komfortowo ze sposobem działania frameworków MVC, powinieneś przejść do dojrzałych i już przetestowanych frameworków.
The table below briefly describes some of the popular PHP frameworks and the features that each framework offers.
| OPIS | |
|---|---|
|
|
It is one of the most popular PHP MVC frameworks, now in its fourth major version (CodeIgniter 4). It’s lightweight and has a short learning curve. It has a rich set of libraries that help build websites and applications rapidly. Users with limited knowledge of OOP programming can also use it. Applications built with CodeIgniter include;
|
|
It’s a Hierarchical Model View Controller (HMVC) secure and lightweight framework. Uwaga: Kohana was officially discontinued in 2017; its last stable release was 3.3.6 (July 2016). The community fork Koseven continued its codebase. Companies that used Kohana include; |
|
It is modeled after Ruby on Rails and remains actively maintained (version 5.x). It’s known for concepts such as software design patterns, convention over configuration, ActiveRecord etc. CakePHP zasilane aplikacje obejmują; |
|
|
Jest to potężna platforma;
It’s ideal for developing business applications. In 2020, Zend Framework transitioned to the open source Laminas Project. Zend/Laminas powered applications include;
Companies that have used the Zend framework include;
|
PHP MVC Framework vs Plain PHP: Key Differences
What does a framework actually change in practice? Plain PHP gives you complete freedom, but every project ends up reinventing routing, validation, and database access from scratch. A PHP MVC framework standardizes these repetitive tasks, so your code stays consistent across projects and teams.
| WYGLĄD | Plain PHP | PHP MVC Framework |
|---|---|---|
| Code organizacja | Mixed HTML, SQL, and logic in single files | Separated into models, views, and controllers |
| Dostęp do bazy danych | Hand-written queries on every page | Built-in query builder or ORM with parameter binding |
| Ochrona | Developer must remember every safeguard | Input filtering, XSS, and CSRF protection included |
| Konserwacja | Changes ripple unpredictably through files | Each layer can change independently |
💡 Wskazówka: Build one small plain PHP project first, like the opinion poll below; the pain of mixed code makes the value of MVC separation obvious.
Przeniesienie aplikacji do sondaży opinii publicznej CodeZapalnik
W tym TutorialStworzyliśmy aplikację ankietową PHP. Tutaj przeniesiemy ten kod do CodeZapalnik
- Do pobrania najnowsza wersja CodeZapalnik od nich stronie internetowej.
- ExtracPrzenieś zawartość spakowanego pliku do katalogu rozwojowego w katalogu serwera WWW. W tej lekcji użyjemy nazwy folderu ciopinionpoll.
- Przejdź do URL http://localhost/ciopinionpoll/
CodeIgniter welcome page above confirms the framework is installed correctly. We are now going to port our opinion poll application to CodeIgniter. Recall that our application was divided into three major components, namely the;
- Kontroler przedni – to część, która reaguje na URL Żąda i zwraca żądaną stronę. Ten kod zostanie przesłany do kontrolera.
- Model – this is the code that responds to data requests and returns the requested data. This code will go into the model
- Widoki – jest to kod odpowiedzialny za formatowanie i wyświetlanie danych. Ten kod zostanie wyświetlony w widoku
Ustawienia konfiguracji bazy danych
To configure the database connection:
- Browse to the ciopinionpoll folder
- Otwórz baza danych.php file located in the application/config directory.
- Znajdź następujące wiersze kodu
- Ustaw nazwę użytkownika na root
- Set the password to your localhost root password
- Set the database name to opinion_poll. Note we will be using the database created in the previous lesson.
- Zapisz zmiany i zamknij plik.
Tworzenie naszego modelu
Następnie utworzymy nasz model, który rozszerzy CI_Model. CI_Model jest częścią CodeBiblioteki Ignitera. Model będzie znajdować się w folderze application/models opinia_poll_model.php
<?php
class Opinion_poll_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function total_votes()
{
$query = $this->db->select('COUNT(choice) as choices_count')->get('js_libraries');
return $query->row()->choices_count;
}
public function get_results()
{
$libraries = array("", "JQuery", "MooTools", "YUI Library", "Glow");
$table_rows = '';
for ($i = 1; $i < 5; $i++)
{
$query = $this->db->select('COUNT(choice) as choices_count')
->where('choice', $i)
->get('js_libraries');
$table_rows .= "<tr><td>" . $libraries[$i] . " Got:</td><td><b>" . $query->row()->choices_count . "</b> votes</td></tr>";
}
return $table_rows;
}
public function add_vote($choice)
{
$ts = date("Y-m-d H:i:s");
$data = array('choice' => $choice, 'ts' => $ts);
$this->db->insert('js_libraries', $data);
}
}
?>
TUTAJ,
- „class Opinion_poll_model rozszerza CI_Model…” to nasz model, który rozszerza CI_Model
- “parent::__construct();” calls the CI_Model constructor
- „$this->load->database();” ładuje bibliotekę bazy danych, dzięki czemu nasza aplikacja może wchodzić w interakcję z bazą danych
- „$this->db->” to CodeAktywny rekord Ignitera. Sprawdź to link aby uzyskać więcej informacji na temat aktywnego rekordu.
Creating Our Controller
Let’s now create the controller. We will use the default CodeIgniter controller located in application/controllers/welcome.php. Replace its source code with the following code.
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('opinion_poll_model');
}
public function index() {
if ($this->input->post('submitbutton') && !$this->input->post('vote')) {
echo "<script>alert('You did not vote!');</script>";
}
if ($this->input->post('vote')) {
$this->opinion_poll_model->add_vote($this->input->post('vote'));
$data['total_votes'] = $this->opinion_poll_model->total_votes();
$data['rows'] = $this->opinion_poll_model->get_results();
$this->load->view('results', $data);
} else {
$this->load->view('opinion_poll_form');
}
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
?>
TUTAJ,
- „if (!definiowane('BASEPATH')) exit('Brak bezpośredniego dostępu do skryptu');” zapewnia, że użytkownicy nie mają bezpośredniego dostępu do klasy kontrolera
- „klasa Welcome rozszerza CI_Controller…” nasz kontroler rozszerza klasę CI_Controller
- “public function __construct()” calls CI_Controller’s class constructor method and loads our Opinion_poll_model model
- “public function index()…” is the function that maps to index.php. It uses CodeKlasa wejściowa Ignitera sprawdza, czy głos został oddany, dodaje go do bazy danych, a następnie wyświetla wyniki. Jeśli tablica postów klasy wejściowej jest pusta, wczytuje stronę głosowania.
- „$this->input->post('…')” to CodeKlasa wejściowa Igniter pobierająca zawartość zmiennej globalnej $_POST.
- „$this->opinion_poll_model->add_vote($this->input->post('vote'))” wywołuje metodę add_vote modelu w celu dodania głosu do bazy danych.
Tworzenie naszych poglądów
Recall from the previous example that we had two HTML pages, one for voting and the other for results. We will use the same HTML code with minimal modifications to create our views. Create the following files in the application/views directory
opinion_poll_form.php
<html>
<head>
<title>
JavaScript Libraries - Opinion Poll
</title>
</head>
<body>
<h2>JavaScript Libraries - Opinion Poll</h2>
<p><b>What is your favorite JavaScript Library?</b></p>
<form method="POST" action="index.php">
<p>
<input type="radio" name="vote" value="1" /> JQuery
<br />
<input type="radio" name="vote" value="2" /> MooTools
<br />
<input type="radio" name="vote" value="3" /> YUI Library
<br />
<input type="radio" name="vote" value="4" /> Glow </p>
<p>
<input type="submit" name="submitbutton" value="OK" />
</p>
</form>
</body>
</html>
Stwórzmy teraz stronę wyników Results.php
<html>
<head>
<title>JavaScript Libraries - Opinion Poll Results</title>
</head>
<body>
<h2>JavaScript Libraries - Opinion Poll Results</h2>
<p><b>What is your favorite JavaScript Library?</b></p>
<p><b><?php echo $total_votes; ?></b> people have thus far taken part in this poll:</p>
<p><table><tr><td>
<?php print($rows); ?>
</tr></td></table></p>
<p><a href="#">Return to voting page</a></p>
</body>
</html>
Testowanie naszej aplikacji
Assuming the root directory of your application is ciopinionpoll, browse to http://localhost/ciopinionpoll/
The voting page above comes from our opinion_poll_form view. Click OK without selecting an option, and you will see the following alert message
Vote for your favorite library, then click on OK. You will see the following results page
This confirms the three layers work together: the controller received the vote, the model stored and counted it, and the view displayed the totals.









