Create and download CSV in PHP
Consider the possibility of quickly creating a CSV file with automatic file download. Consider the formation, separators and header for the ability to download the file.
Don't judge too harshly, to show an example of how MVC works, I wrote a simple code in 20 minutes based on a path split in a link. We will analyze everything using the example of a local link:
http://test1.loc/product/test-product
Our project structure will consist of 4 folders and several php files.
1. .htaccess:
This is the very first file that fires when a user logs in, back at the apache level.
AddDefaultCharset UTF-8
Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1&%{QUERY_STRING} [L]
Apache must have mod_rewrite installed.
RewriteRule ^index\.php$ - [L] // - Says that the main startup file is index.php. It is not necessary to specify it in the url now.
RewriteRule ^(.*)$ /index.php?path=$1&%{QUERY_STRING} [L] // - the entire path (product/test-product) goes into the $_GET parameter, which we will then split into routes.
2. index.php:
This is the startup file where I placed the error handling and the launch of the next step.
<?php
if (strpos($_SERVER['REQUEST_URI'], '.php') !== false) {
header("Location:http://" . $_SERVER['SERVER_NAME']);
exit;
}
define('ENVIRONMENT', 'development');
switch (ENVIRONMENT) {
case 'development':
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
ini_set('display_errors', 'on');
break;
case 'testing':
case 'production':
error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED ^ E_STRICT ^ E_WARNING);
ini_set('display_errors', 'off');
break;
default:
header('HTTP/1.1 503 Service Unavailable.', TRUE, 503);
exit('The application environment is not set correctly.');
}
define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']);
define('SERVER_NAME ', $_SERVER['SERVER_NAME']);
require_once DOCUMENT_ROOT.'/system/router.php';
new Router();
Here we declare constants and run the class Router();
3. system/router.php:
The main router that divides the link into array segments and starts the controller on the name of the first segment of the link. The first segment of the link is "product". Therefore, product.php
will be loaded
<?php
if (!defined('DOCUMENT_ROOT')) {
exit('No direct script access allowed');
}
class Router {
private $full_path ='';
private $array_path = array();
public function __construct() {
$this->parse_path();
}
private function parse_path() {
$this->full_path = $_GET['path'];
$this->array_path = explode('/', $_GET['path']);
unset($_GET['path']);
if (file_exists(DOCUMENT_ROOT . '/controller/'.$this->array_path[0] . '.php')) {
  ; require_once DOCUMENT_ROOT . '/controller/' . $this->array_path[0] . '.php';
if (class_exists($this->array_path[0])) {
$class = new $this->array_path[0]($this->array_path);
$class->index();
}
}
}
}
!defined('DOCUMENT_ROOT') - will not let you run the php file directly.
parse_path() - we parse the $_GET['path'] url that comes from htaccess into the file path and run index().
4. controller/product.php:
Controller handler. We will place the logic for processing the model and view in it. The first segment of the link is "product". Therefore, this file is loaded. Further, I think it is clear why "product_model.php" and "product_view.php"
are loaded
<?php
if (!defined('DOCUMENT_ROOT')) {
exit('No direct script access allowed');
}
/**
* Calculation and logic processing controller
*/
class product {
private $array_path = array();
public function __construct($path) {
$this->array_path = $path;
}
public function index() {
$dataProduct = $this->connectPhp('model');
$this->includeFile('view', ['dataProduct' => $dataProduct]);
}
private function connectPhp($folder) {
if ($this->includeFile($folder)) {
if (class_exists($this->array_path[0] . '_' . $folder)) {
  ; $name = $this->array_path[0] . '_' . $folder;
$class = new $name($this->array_path);
return $class->index();
}
}
}
private function includeFile($folder, $data = false) {
if (file_exists(DOCUMENT_ROOT . '/' . $folder . '/' . $this->array_path[0]. '_' . $folder . '.php')) {
  ; include DOCUMENT_ROOT . '/' . $folder. '/' . $this->array_path[0]. '_' . $folder. '.php';
return TRUE;
}
return FALSE;
}
}
in index() we connect the model and connect the view, in which we use the received variable $dataProduct.
5. model/product_model.php:
This model will be responsible for processing requests to the database. We will place everything related to connections and requests in it.
<?php
if (!defined('DOCUMENT_ROOT')) {
exit('No direct script access allowed');
}
/**
* Model for manipulating database queries
*/< br />class product_model {
private $array_path = array();
public function __construct($path) {
$this->array_path = $path;
}
public function index() {
$this->dbConnect();
return $this->getProduct();
}
private function dbConnect() {
// Connect to the database here
}
private function getProduct() {
// Retrieve something related to the product $this->array_path[1];
return 'Product test test';
}
}
The model is empty, didn't fill it in, just returned a string for an example MVC structure. This also runs index() and returns a string.
6.view/product_view.php:
Html page output. The view itself is formed, which will be available to the user.
<html>
<head>
<title>Main Page - About Me</title>
</head>
<body>
<center><h1><?php echo $data['dataProduct']; ?></h1></center>
<center><h2>Product Description</h2></center>
</body>
</html>
We pass the string that came from the model in the $data array. We output and everything is cool.
As a result, we will have a regular page.
Do not judge strictly, because I did not set the task to show the correct code or the correct class structure. Found inspiration to explain about MVC.
Consider the possibility of quickly creating a CSV file with automatic file download. Consider the formation, separators and header for the ability to download the file.
Latest templates from ImageCMS 4.12, authorization is required to download.
Consider options for popular options for storing goods in a shopping cart in an online store. Let's outline the pros and cons of such storage. Consider options for long-term storage of the basket.
Creating a key for imageCMS 4.9-4.12.1 Pro and Pre. You must be logged in to receive it.
When running the script from the console, there is no DOCUMENT_ROOT in $_SERVER. Let's try to get around this in our own ways, catch the file directory.
After developing any tool in PHP, the question becomes how resourceful the created code is and what elements it still affects. Let's take a look at xhprof installation, configuration, and how to work with xhprof.
Let's analyze the possibility of combining conditions in a query by groups in Propel. Consider an example of filtering by fields using ->condition() and ->combine().
Faced the problem of authorization 1s on the site. For some reason, the server did not accept the PHP_AUTH_USER and PHP_AUTH_PW parameters from it. Let's take a closer look at the solution and bypassing these parameters in $_SERVER .
Файзулла
Немного ясно стало, но не совсем... в частности как соединять фронтенд с бакэндом
я хочу сайт сделать на РНР без шаблонизатора и фрэймворка, но в MVC/
Поможете? и вам материал на сайт будет )))
В общем view/product_view.php это и есть подключаемая фронтовая страница.
Для каждого контроллера можно создать свой фронтовый php файл. Можно поиграться с расширением структуры на namespace.
Я привел только стркутурный пример, чтобы показать что такое MVC. Так же есть еще HMVC, но не будем углубляться)
В любом случае тема эта большая и должна исходить из задачи, которую желают видеть в проекте)
Можно разобрать какай-то индивидуальный пример для Вас, отпишите через обратную связь если есть желание)