How to set up smartphones and PCs. Informational portal
  • home
  • Interesting
  • Mail sending methods. Implementation of descendant classes Model and Controller, creation of View's

Mail sending methods. Implementation of descendant classes Model and Controller, creation of View's

05/22/06 83.2K

Have you ever wanted to install a form on your website? feedback? Surely you have encountered similar scripts. Oddly enough, ready-made scripts for sending a form by email are very popular (you can see this in any archive of scripts), and there are a great many of them. There are simple ones in which nothing changes, and there are complex ones large systems, which operate on mysql, allow you to dynamically change any fields, contain a bunch of settings... But are they really needed? In my opinion, the need for similar systems very doubtful.

Test sending mail to home computer it won't work out. To do this, you need hosting with PHP support and mail sending functions. I recommend you the hosting provider runweb.ru. This provider offers great rates, highest speed access and excellent service.

Mail sending methods

There are two main ways to send mail from a server using PHP.
I want to look at both of these methods in order.

The first and simplest is to use php functions mail(). The function is very simple and straightforward, although sending mail from using mail() also has a number of disadvantages. The most important thing is that the letter is sent not directly, but through PHP. At the same time, the php program inserts some of its fields into the letter. For example, you will not be able to correctly indicate the sender. In most cases, the “from” field (that is, from whom the letter came) will contain the server name. The thing is that PHP inserts its headers into the service line of the "from" letter.

However, sending mail using the mail() function remains the simplest
way to send a letter from the server. Let's look at this method in more detail.

The mail() function has the following syntax:

mail($to, $subject, $body, $headers);

$to is the recipient's address. For example, " [email protected]". $subject - the subject of the letter. For example, "You have received a letter." $body - the text of the message. $headers - any headers of the letter. For example, the sender's address will look like this: "from: [email protected]".

Here complete example sending mail using mail():

mail(" [email protected]", "Subject of the letter", "Hello! nYou have received a letter.", "from: site_name");

Please note that when using this function on a home computer, it may throw an error because it cannot send an email without a mail server.

Now let's see how you can send an email using sendmail.

sendmail is standard program operating system unix that sends mail.
php can run unix programs by using the pipes tool. This unix tool allows you to send data from one program to another, similar to how we write to a file. Only the file in this case is the program (in particular, sendmail), which receives the data.

The sendmail program has many parameters, we will use some of them. To use sendmail, you need to open a pipe to it. In php this is done using the popen() command, which is identical in syntax to the fopen() command. By using popen() we open a stream to sendmail
to write to it (remember the mode parameter "w"?), after which you can send data to it regular command fputs(). Let's see what the complete procedure for sending a letter via sendmail looks like:

In this program, the first thing we do is describe rfc headers. rfc are service fields that contain all the information about the letter. You can see an example of rfc, for example, in the program bat! by clicking right click mouse on the text of the letter and selecting "rfc-822 headers" (the name of the item may differ). To remove them, repeat the steps. In the header we describe the "content-type" fields, which indicate that the letter is text and in windows-1251 encoding (standard windows encoding). "koi8-r" can also be used as an encoding, this is a standard unix encoding. In this article we will not consider possible rfc headers in detail. We'll do it a little later,
when we get closer to working with mail. So, after we have described the service variables and letter headers, we open sendmail. Pay attention to the path to the program "/usr/sbin/sendmail". On different servers it may differ!
If this line doesn't work, ask your ISP where sendmail is located. The following parameters are specified: "-i -f$from - $recipients". These are standard parameters for sending a letter and two fields are inserted into them: $from - from whom, $recipients - recipient addresses. In our case, the $recipients variable contains only one address. In fact, you can use multiple addresses, separated by a space:

$recipients = " [email protected] [email protected] [email protected]";

Next, we first write the message headers into the stream (the $text_headers variable), then we separate them with a line break and write the message text. Last step— closing the stream and checking for errors. If executed correctly, a zero is placed in the $result variable, and if an error occurs, the error number is written to it.

Now let's look at an example of using the mail sending capabilities. To do this, we will make a feedback form that you can install on your website. We will use sendmail as the method for sending a letter.

Creating a feedback form

Our feedback form will be one script. This script will display the form and send the email.

contact.php:

Feedback

Direct connection
Your name: *
Your email: *
Your website:
Your message: *

Fields marked with an asterisk (*) must be completed.

Now let's look at how this program works. Execution begins with the line “if (!$a) show_form();”, since before this a function is specified, which, of course, is not executed. In this line we check whether there was an attempt to fill out the form (from the form, as you can see, the $a variable is passed, which is checked in this line). If no such attempt was made, the show_form() function is called, which displays the form.

Lately, I have been increasingly confronted with mediocrity in IT. Friends seek advice, and when you begin to understand the subject matter, your hair begins to stand on end in all possible places. Finding out how much friends paid for similar services, you experience an attack of shock.

Tens of thousands of rubles are simply thrown away and instead of simplification, business owners end up with additional problems. Perhaps someone will see the problems of their organization in the note and will be able to draw appropriate conclusions.

There are people who like to scold everyone and extol their knowledge. There are such “lefties” in every field. Perhaps they have gone through fire, water and copper pipes in their practice and have every right to talk like that. In the field of information technology, it is difficult to meet people who fit this description. There are too many technologies and it is impossible to be an expert in absolutely everything.

A person can be an expert in several areas, but not in all. For example, most of my work involves software development. I feel much more confident in this area than in system administration. I will never argue with a tough admin about the nuances of packet routing, because... I myself have superficial knowledge.

It won't be difficult for me to set up server components, set up a FireWall or an Internet gateway, but I don't try to spend time studying the layers of the OSI model in detail. I’m not the least bit ashamed of this, because... I'm more interested in another area.

Today I had a chance to talk with such a know-it-all in the field of databases. A man who proudly called himself a professional completely ruined the CIS database and did not even think about admitting his guilt. He was just doing an update and something went wrong. Backup He didn’t want to do any updates before installing the updates (really, why?) and when a problem arose, he didn’t bother racking his brains. I just uploaded a copy from a month ago and reported on the work done.

Cool? I almost fell out of my chair from such professionalism. Not only was the policy not created Reserve copy, so this craftsman didn’t bother to make a copy before such important operation like updating the database structure. It turned out that forgetfulness was not his main problem.

I took the phone number of this specialist and decided to call him personally. You never know, suddenly the person had good reasons to make this decision. It would be better not to call. There were no reasons, but there was a whole lot of incompetence and lack of basic knowledge.

He stupidly tried to justify himself, and my questions only caused surprise. Imagine, he told me that the program does not use any tables. Everything is stored in one single file. These words completely killed the pieces of faith in me for a positive outcome. He was the one who told me about FireBird.

Since everything is stored in one file and the program cannot “read” this file, then you just need to return to old copy. Why try to figure out the problem and at least get it out? important information directly from tables? There was no point in continuing the conversation any further. The specialist simply killed people’s work in one fell swoop in half a month and received a reward.

If your organization is not ready to employ a full-time IT specialist, then I strongly recommend that you take care of documenting your strategy for interacting with a coming person. It is necessary to establish his responsibilities on paper and have a list of infrastructure facilities for which he is responsible.

This will not save you from problems, but it will give you a clear understanding of what a person does and which areas of his work require increased attention. For example, if you do not understand IT, and your company has databases on which the life of the organization depends, then do not skimp on purchasing professional program for backup. Let the visiting specialist set it up, and you will receive daily reports by email about the results of the backup.

It was not by chance that I started talking about software, because... in practice, I felt that not all IT specialists are ready to automate the backup process. They either take responsibility for creating copies themselves, or simply play Russian roulette. As a result, the only loser from this situation is you, the head of the company.

I feel hopeless, when it seems that everything is meaningless and will lead to nothing, the collapse of life. This feeling when one gives up and any thoughts or actions designed to reassure or change something are discarded as useless. I am accompanied by a feeling of loneliness, when it seems that no one needs me with my problems and troubles.

Before, I didn’t do anything at all to make it easier, but, on the contrary, I’m starting to feel sorry for myself, because I feel bad, I don’t want anything and nothing makes me happy.

Today I occupy myself with some activities: for example, cleaning the house, playing computer games.

I’m curious myself about how feelings are lived, because I probably don’t know how to live them.

Hopelessness.

Only once in my life have I experienced such a feeling!

I was about 15 years old.

During my next visit to one of the trainings, I was filled with strong confidence in my abilities, I achieved success time after time...

And here it is, a situation, a task with three characters, a situation is being played out... banal, as it seemed to me then.

For me, hopelessness is the lack of desire to do anything, complete depression and indifference to everything, depression.

I don’t want to live this feeling, because in this state everything ceases to be important for me and I give up. I don't run away and I don't silence it.

Previously, I just lived with it and used it, but now I know that there is a way out of any situation and the Sun will help me find it. I didn’t pay attention to whether I was inclined to verbalize the feeling of hopelessness to other people, but I definitely don’t always admit it to myself, although over time it becomes obvious. I want to learn to see a way out of situations so that even thoughts do not appear that there is no way out.

Hopelessness is when I don’t see a way out and I give up, I don’t want to do anything, because I don’t see the point in it, when there is no hope, which, in theory, should be the last to die.

I definitely don’t want to live this feeling, but there is always a way out, just like in drug addiction, from which I did not see a way out, but thanks to the Armed Forces and the people who showed it to me, today I am sober, with God, with you. Hopelessness is a difficult feeling, I try to delegate and find a way out, because there are no hopeless situations. Faith helps a lot. Now I know that admitting a situation is hopeless means giving up and doing nothing, so don't be a pessimist. In any negative you can find a positive - there is a way out of any hopeless situation.

This tutorial will show you how to create the simplest contact form for an HTML template.

First of all, create 2 files: contact_form.html and contact.php. The first file will contain the code for your contact form, and the second will process the data from this form.

HTML

Below is an example of HTML code contact form:

Your name

Your e-mail

Message

In the browser it will look like this:

Let's take a quick look at the main aspects of this form. The tag must have 2 additional attributes:

action="contact.php" - determines where to send data from the contact form after sending the letter.

method="post" - defines how to send data from the contact form to a file, specified by attribute action. Tags must have a "name" attribute with a unique identifier. This attribute is used to identify contact form data after an email has been sent. There are also 2 additional elements to note that are used as the Submit and Clear buttons, the first element should be defined by the type="submit" tag and the second by the type="reset" tag.

The procedure for creating a contact form is quite simple.

PHP

Let's move on to creating a contact.php file that will collect data from the contact form, compose it into a message and send it by email. Download the finished contact.php file from this link. Below is the code of the file with comments to its main sections:

Assigning data from each contact form field (cf_name, cf_email, cf_message) to the following PHP variables ($cf_message, $field_email, $field_message) $field_name = $_POST["cf_name"]; $field_email = $_POST["cf_email"]; $field_message = $_POST["cf_message"];

The $mail_to function should contain the email of the site owner, this is exactly the address where messages will be sent. You can specify several email addresses at once, separating them with a comma (for example, [email protected], [email protected])

$mail_to = " [email protected]";

Subject of the letter you will receive:

$subject = "Message from a site visitor " . $field_name;

Building a message structure:

$body_message = "From: ".$field_name."\n"; $body_message .= "E-mail: ".$field_email."\n"; $body_message .= "Message: ".$field_message;

Construction of message headers:

$headers = "From: $cf_email\r\n"; $headers .= "Reply-To: $cf_email\r\n";

We define the mail() function and assign it to the $mail_status variable, which is used to check whether the letter was sent successfully.

$mail_status = mail($mail_to, $subject, $body_message, $headers);

If the mail() function succeeds then use the code below:

If ($mail_status) ( ?> // Print a message alert("Thank you you for the message. We will contact you shortly."); // Redirect to some page of the site. You can also specify full URL, e.g. http://template-help.com window.location = "contact_page.html"; // Print a message alert("Message failed. Please, send an email to [email protected]"); // Redirect to some page of the site. You can also specify full URL, e.g. http://template-help.com window.location = "contact_page.html";

You can download ready files contact_form.html and contact.php

Many people start writing a project to work with a single task, not implying that it can grow into a multi-user management system, for example, content or, God forbid, production. And everything seems great and cool, everything works, until you begin to understand that the code that is written consists entirely of crutches and hardcode. The code is mixed with layout, queries and crutches, sometimes even unreadable. A pressing problem arises: when adding new features, you have to tinker with this code for a very long time, remembering “what was written there?” and curse yourself in the past.

You may have even heard about design patterns and even leafed through these wonderful books:

  • E. Gamma, R. Helm, R. Johnson, J. Vlissides “Object-oriented design techniques. Design Patterns";
  • M. Fowler "Architecture of Enterprise Software Applications."
And many, undaunted by the huge manuals and documentation, tried to study any of the modern frameworks and, faced with the complexity of understanding (due to the presence of many architectural concepts cleverly interconnected), put off the study and use of modern tools in a “shelter.”

This article will be useful primarily for beginners. In any case, I hope that in a couple of hours you will be able to get an idea of ​​the implementation of the MVC pattern, which underlies all modern web frameworks, and also get “food” for further reflection on “how to do it.” At the end of the article there is a selection useful links, which will also help you understand what web frameworks consist of (besides MVC) and how they work.

Seasoned PHP programmers are unlikely to find anything new for themselves in this article, but their comments and comments on the main text would be very helpful! Because Without theory, practice is impossible, and without practice, theory is useless, then first there will be a little theory, and then we will move on to practice. If you are already familiar with the MVC concept, you can skip the theory section and go straight to the practice.

1. Theory The MVC pattern describes a simple way to structure an application, the purpose of which is to separate business logic from the user interface. As a result, the application is easier to scale, test, maintain and, of course, implement.

Let's look at the conceptual diagram of the MVC pattern (in my opinion, this is the most successful diagram I have seen):

In architecture MVC model provides data and business logic rules, the view is responsible for user interface, and the controller provides interaction between the model and the view.

A typical flow of an MVC application can be described as follows:

  • When a user visits a web resource, the initialization script creates an instance of the application and launches it for execution.
    This displays a view of, say, the main page of the site.
  • The application receives a request from the user and determines the requested controller and action. In the case of the main page, the default action is performed ( index).
  • The application instantiates the controller and runs the action method,
    which, for example, contains model calls that read information from the database.
  • After this, the action creates a view with the data obtained from the model and displays the result to the user.
  • Model - contains the business logic of the application and includes methods for sampling (these can be ORM methods), processing (for example, validation rules) and providing specific data, which often makes it very thick, which is quite normal.
    The model should not directly interact with the user. All variables related to the user request must be processed in the controller.
    The model should not generate HTML or other display code that can change depending on the user's needs. Such code should be processed in views.
    The same model, for example: the user authentication model can be used in both the user and administrative parts of the application. In this case, you can move the general code into a separate class and inherit from it, defining sub-application-specific methods in its descendants.

    View - used to specify the external display of data received from the controller and model.
    Views contain HTML markup and small inserts of PHP code to traverse, format, and display data.
    Should not directly access the database. This is what models should do.
    Should not work with data obtained from a user request. This task must be performed by the controller.
    Can directly access properties and methods of a controller or models to obtain output-ready data.
    Views are usually divided into a common template, containing markup common to all pages (for example, a header and footer) and parts of the template that are used to display data output from the model or display data entry forms.

    The controller is the glue that connects models, views and other components into working application. The controller is responsible for processing user requests. The controller should not contain SQL queries. It is better to keep them in models. The controller should not contain HTML or other markup. It’s worth bringing it into view.
    In a well-designed MVC application, controllers are usually very thin and contain only a few dozen lines of code. The same cannot be said about Stupid Fat Controllers (SFC) in CMS Joomla. The controller logic is quite typical and most of it is transferred to base classes.
    Models, on the contrary, are very thick and contain most of the code related to data processing, because the data structure and business logic contained within it are usually quite specific to a particular application.

    1.1. Front Controller and Page Controller In most cases, user interaction with a web application occurs through clicking on links. Look now at the address bar of your browser - you received this text from this link. Other links, such as those on the right side of this page, will provide you with different content. Thus, the link represents a specific command to the web application.

    I hope you have already noticed that different sites can have perfect different formats construction address bar. Each format can display the architecture of a web application. Although this is not always the case, in most cases it is a clear fact.

    Let's consider two options for the address bar, which display some text and a user profile.

    Approximate processing code in this case:
    switch($_GET["action"]) ( case "about" : require_once("about.php"); // "About Us" page break; case "contacts" : require_once("contacts.php"); // "Contacts" page break; case "feedback" : require_once("feedback.php"); // "Feedback" page break; default: require_once("page404.php"); // page "404" break; )
    I think almost everyone has done this before.

    Using a URL routing engine, you can configure your application to accept requests like this to display the same information:
    http://www.example.com/contacts/feedback

    Here contacts represents the controller, and feedback is the contacts controller method that displays the feedback form, etc. We will return to this issue in the practical part.

    It's also worth knowing that many web frameworks' routers allow you to create custom URL routes (specify what each part of the URL means) and rules for processing them.
    Now we have sufficient theoretical knowledge to move on to practice.

    2. Practice First, let's create the following file and folder structure:


    Looking ahead, I will say that the core classes Model, View and Controller will be stored in the core folder.
    Their children will be stored in the controllers, models and views directories. The index.php file is the entry point into the application. The bootstrap.php file initiates the loading of the application, connecting all the necessary modules, etc.

    We will go sequentially; Let's open the index.php file and fill it with the following code:
    ini_set("display_errors", 1); require_once "application/bootstrap.php";
    There shouldn't be any questions here.

    Next, let's immediately go to the bootstrap.php file:
    require_once "core/model.php"; require_once "core/view.php"; require_once "core/controller.php"; require_once "core/route.php"; Route::start(); //start the router
    The first three lines will connect for now non-existent files kernels. The last lines include the file with the router class and launch it for execution by calling the static start method.

    2.1. Implementing a URL Router Let's deviate from the implementation for now MVC pattern and let's do routing. The first step we need to do is write the following code in .htaccess:
    RewriteEngine On RewriteCond %(REQUEST_FILENAME) !-f RewriteCond %(REQUEST_FILENAME) !-d RewriteRule .* index.php [L]
    This code will redirect all page processing to index.php, which is what we need. Remember in the first part we talked about Front Controller?!

    We will place the routing in a separate file route.php in the core directory. In this file we will describe the Route class, which will run controller methods, which in turn will generate the page view.

    Contents of the route.php file

    class Route ( static function start() ( // controller and default action $controller_name = "Main"; $action_name = "index"; $routes = explode("/", $_SERVER["REQUEST_URI"]); // get the controller name if (!empty($routes)) ( $controller_name = $routes; ) // get the action name if (!empty($routes)) ( $action_name = $routes; ) // add prefixes $model_name = " Model_".$controller_name; $controller_name = "Controller_".$controller_name; $action_name = "action_".$action_name; // hook up the file with the model class (there may not be a model file) $model_file = strtolower($model_name). ".php"; $model_path = "application/models/".$model_file; if(file_exists($model_path)) ( include "application/models/".$model_file; ) // hook up the file with the controller class $controller_file = strtolower ($controller_name)..php"; $controller_path = "application/controllers/".$controller_file; if(file_exists($controller_path)) ( include "application/controllers/".$controller_file; ) else ( /* it would be correct to throw an exception here, but to simplify things, we’ll immediately redirect to the 404 page */ Route::ErrorPage404(); ) // create a controller $controller = new $controller_name; $action = $action_name; if(method_exists($controller, $action)) ( // call the controller action $controller->$action(); ) else ( // here it would also be wiser to throw an exception Route::ErrorPage404(); ) ) function ErrorPage404( ) ( $host = "http://".$_SERVER["HTTP_HOST"]."/"; header("HTTP/1.1 404 Not Found"); header("Status: 404 Not Found"); header("Location:".$host."404"); ) )


    I note that the class implements very simplified logic (despite the voluminous code) and may even have security problems. This was done intentionally, because... writing a full-fledged routing class deserves at least a separate article. Let's look at the main points...

    The global array element $_SERVER["REQUEST_URI"] contains the full address to which the user contacted.
    For example: example.ru/contacts/feedback

    Using the function explode The address is divided into components. As a result, we get the name of the controller, for the example given, this is controller contacts and the name of the action, in our case - feedback.

    Next, the model file (the model may be missing) and the controller file, if any, are connected and finally, an instance of the controller is created and the action is called, again, if it was described in the controller class.

    Thus, when going to, for example, the address:
    example.com/portfolio
    or
    example.com/portfolio/index
    The router will perform the following actions:

  • will include the model_portfolio.php file from the models folder, containing the Model_Portfolio class;
  • will include the controller_portfolio.php file from the controllers folder, containing the Controller_Portfolio class;
  • will create an instance of the Controller_Portfolio class and call the default action - action_index, described in it.
  • If the user tries to access the address of a non-existent controller, for example:
    example.com/ufo
    then he will be redirected to the “404” page:
    example.com/404
    The same thing will happen if the user accesses an action that is not described in the controller.2.2. Let's return to the MVC implementation Let's go to the core folder and add three more files to the route.php file: model.php, view.php and controller.php


    Let me remind you that they will contain base classes, which we will now begin writing.

    Contents of the model.php file
    class Model ( public function get_data() ( ) )
    The model class contains a single empty data fetch method, which will be overridden in descendant classes. When we create descendant classes everything will become clearer.

    Contents of the view.php file
    class View ( //public $template_view; // here you can specify the default general view. function generate($content_view, $template_view, $data = null) ( /* if(is_array($data)) ( // convert array elements into variables extract($data); ) */ include "application/views/".$template_view; ) )
    It is not difficult to guess that the method generate intended to form a view. The following parameters are passed to it:

  • $content_file - views displaying page content;
  • $template_file - template common to all pages;
  • $data is an array containing page content elements. Usually filled in in the model.
  • The include function dynamically connects a general template (view) within which the view will be embedded
    to display the content of a specific page.

    In our case, the general template will contain header, menu, sidebar and footer, and the content of the pages will be contained in separate form. Again, this is done for simplicity.

    Contents of the controller.php file
    class Controller ( public $model; public $view; function __construct() ( $this->view = new View(); ) function action_index() ( ) )
    Method action_index- this is an action called by default; we will override it when implementing descendant classes.

    2.3. Implementation of the descendant classes Model and Controller, creation of View "s Now the fun begins! Our business card website will consist of the following pages:
  • home
  • Services
  • Portfolio
  • Contacts
  • And also - the “404” page
  • Each page has its own controller from the controllers folder and a view from the views folder. Some pages may use a model or models from the models folder.


    In the previous figure, the file template_view.php is highlighted separately - this is a template containing markup common to all pages. In the simplest case it could look like this:
    home
    To give the site a presentable look, we design CSS template and integrate it into our website by changing the structure of the HTML markup and CSS connections and JavaScript files:

    At the end of the article, in the “Result” section, there is a link to a GitHub repository with a project in which steps have been taken to integrate a simple template.

    2.3.1. Creating the main page Let's start with the controller controller_main.php , here is its code:
    class Controller_Main extends Controller ( function action_index() ( $this->view->generate("main_view.php", "template_view.php"); ) )
    In method generate an instance of the View class, the names of the files of the general template and the view with the page content are passed.
    In addition to the index action, the controller can of course contain other actions.

    File with general view we looked at earlier. Consider the content file main_view.php:
    Welcome!

    OLOLOSHA TEAM is a team of first-class specialists in the field of website development with many years of experience in collecting Mexican masks, bronze and stone statues from India and Ceylon, bas-reliefs and sculptures created by masters of Equatorial Africa five or six centuries ago...


    This contains simple markup without any PHP calls.
    To display main page You can use one of the following addresses:

    We will consider an example using a view displaying data obtained from the model below.

    2.3.2. Create a “Portfolio” page In our case, the “Portfolio” page is the only page that uses the model.
    The model usually includes data sampling methods, for example:
  • methods of native pgsql or mysql libraries;
  • methods of libraries that implement data abstraction. For example, methods of the PEAR MDB2 library;
  • ORM methods;
  • methods for working with NoSQL;
  • and etc.
  • For simplicity, we will not use SQL queries or ORM statements here. Instead, we will emulate real data and immediately return an array of results.
    Place the model file model_portfolio.php in models folder. Here are its contents:
    class Model_Portfolio extends Model ( public function get_data() ( return array(array("Year" => "2012", "Site" => "http://DunkelBeer.ru", "Description" => "Promotional site of the dark Dunkel beer from the German manufacturer Löwenbraü produced in Russia by the brewing company "SUN InBev."), array("Year" => "2012", "Site" => "http://ZopoMobile.ru", "Description" => "Russian-language catalog Chinese phones Zopo company on Android based OS and accessories for them."), // todo); ) )

    The model controller class is contained in the controller_portfolio.php file, here is its code:
    class Controller_Portfolio extends Controller ( function __construct() ( $this->model = new Model_Portfolio(); $this->view = new View(); ) function action_index() ( $data = $this->model->get_data( ); $this->view->generate("portfolio_view.php", "template_view.php", $data); ) )
    To a variable data the array returned by the method is written get_data which we looked at earlier.
    This variable is then passed as a method parameter generate, which also contains: the name of the file with the general template and the name of the file containing the view with the page content.

    The view containing the page content is in the portfolio_view.php file.
    Portfolio

    All projects in the following table are fictitious, so do not even try to follow the links provided.
    YearProjectDescription


    Everything is simple here, the view displays the data obtained from the model.

    2.3.3. Creating the remaining pages The remaining pages are created in the same way. Their code is available in the GitHub repository, a link to which is provided at the end of the article, in the “Result” section.3. Result Here's what happened in the end:

    Screenshot of the resulting business card website



    GitHub link: https://github.com/vitalyswipe/tinymvc/zipball/v0.1

    But in this version I sketched out the following classes (and their corresponding types):

    • Controller_Login in which a view is generated with a form for entering login and password, after filling which the authentication procedure is performed and, if successful, the user is redirected to the admin panel.
    • Contorller_Admin with an index action that checks whether the user was previously authorized on the site as an administrator (if so, the admin panel view is displayed) and a logout action for logging out.
    Authentication and authorization is a different topic, so it is not discussed here, but only the link given above is provided so that you have something to start from.4. Conclusion The MVC pattern is used as an architectural basis in many frameworks and CMSs that were created in order to be able to develop qualitatively more complex solutions in a shorter period of time. This was made possible by increasing the level of abstraction, since there is a limit to the complexity of the structures that the human brain can operate with.

    But, using web frameworks such as Yii or Kohana, consisting of several hundred files, when developing simple web applications (for example, business card sites) is not always advisable. Now we can create a beautiful MVC model so as not to mix Php, Html, CSS and JavaScript code in one file.

    This article is more of a starting point for learning CMF than an example of something truly correct that you can use as the basis for your web application. Perhaps it even inspired you and you are already thinking about writing your own microframework or CMS based on MVC. But, before reinventing the next wheel with “blackjack and whores,” think again: maybe it would be more reasonable to direct your efforts to the development and helping the community of an already existing project?!

    P.S.: The article was rewritten taking into account some comments left in the comments. The criticism turned out to be very useful. Judging by the response: comments, PMs and the number of users who added the post to favorites, the idea of ​​writing this post turned out to be not so bad. Unfortunately, it is not possible to take into account all the wishes and write more and in more detail due to lack of time... but perhaps those mysterious individuals who downvoted the original version will do this. Good luck with your projects!

    5. A selection of useful links on the subject The article very often touches on the topic of web frameworks - this is a very broad topic, because even microframeworks consist of many components cleverly interconnected and it would take more than one article to talk about these components. However, I decided to bring here small selection links (which I followed when writing this article) that in one way or another relate to the topic of frameworks.

    Tags: Add tags

    Best articles on the topic