Created
May 11, 2017 22:32
-
-
Save Vermorr/9589b2c5799b0122c049e2710aa2fcaa to your computer and use it in GitHub Desktop.
php1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RewriteEngine On | |
RewriteBase / | |
RewriteRule ^(.*)$ index\.php |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="ProjectModuleManager"> | |
<modules> | |
<module fileurl="file://$PROJECT_DIR$/.idea/php1.loc.iml" filepath="$PROJECT_DIR$/.idea/php1.loc.iml" /> | |
</modules> | |
</component> | |
</project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<module type="WEB_MODULE" version="4"> | |
<component name="NewModuleRootManager"> | |
<content url="file://$MODULE_DIR$" /> | |
<orderEntry type="inheritedJdk" /> | |
<orderEntry type="sourceFolder" forTests="false" /> | |
</component> | |
</module> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project version="4"> | |
<component name="VcsDirectoryMappings"> | |
<mapping directory="$PROJECT_DIR$" vcs="Git" /> | |
</component> | |
</project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Router | |
{ | |
private $routes; | |
public function __construct() | |
{ | |
$routsPath = ROOT.'/config/routes.php'; //путь к файлу с роутами | |
$this->routes = include($routsPath);//присваеваем свойству routes массив, который находится в файле routes.php | |
} | |
/* | |
* Метод возвращает строку запроса | |
* */ | |
private function getURI() | |
{ | |
if (!empty($_SERVER['REQUEST_URI'])){ | |
return trim($_SERVER['REQUEST_URI'], '/'); | |
} | |
} | |
/** | |
* | |
*/ | |
public function run() //принимает управление от фронт-контроллера | |
{ | |
//Получить строку запроса, вынесли в метод getURI | |
$uri = $this->getURI(); | |
/* | |
* Проверить наличие такого запроса в routes.php | |
* для каждого маршрута, который в нашем массиве мы помещаем | |
* в переменную $uriPattern строку запроса,а | |
* в переменную $path путь обработчика | |
*/ | |
foreach ($this->routes as $uriPattern => $path) { | |
//echo "<br>$uriPattern -> $path"; | |
//сравнием $uriPattern и $uri | |
//Если есть совпадение, определить какой контроллер и | |
// action обрабатывают запрос | |
if (preg_match("~$uriPattern~", $uri)){ | |
// echo '<br>Где ищем (запрос, который набрал пользователь): '.$uri; | |
// echo '<br>Что ищем (совпдения из правил): '.$uriPattern; | |
// echo '<br>Кто обрабатывает: '.$path; | |
//Получаем внутренний путь из внешнего согласно правилу. | |
$internalRoute = preg_replace("~$uriPattern~", $path, $uri); | |
// echo '<br><br>Нужно сформировать: '.$internalRoute; | |
//определим, какой контроллер и action обрабатывает запрос | |
//функция explode('/', $path); разделяет строку на 2 части | |
$segments = explode('/', $internalRoute); | |
//мы можем получить имя контроллера | |
$controllerName = array_shift($segments).'Controller'; | |
//ф-я array_shift выводит перевый элемент массива и удаляет его | |
$controllerName = ucfirst($controllerName); | |
//ф-я ucfirst первую букву переводи в верхний регистр | |
//также мы можем получить имя action | |
$actionName = 'action'.ucfirst(array_shift($segments)); | |
//echo $actionName; | |
//echo '<br>Класс или controller: '.$controllerName; | |
//echo '<br>Метод или action: '.$actionName; | |
$parameters = $segments; | |
//Подключить файл класса контроллера | |
$controllerFile = ROOT.'/controllers/'.$controllerName.'.php'; | |
if (file_exists($controllerFile)){ | |
include_once($controllerFile); | |
} | |
//Создать объект, вызвать метод (т.е. action) | |
$controllerObject = new $controllerName; | |
//$result = $controllerObject->$actionName($parameters); | |
// Функция вызывает вызвает action, которая содержится в переменоой $actionName | |
// у объекта $controllerObject при этом передаёт ему массив с параметрами ($parameters) | |
$result = call_user_func_array(array($controllerObject, $actionName), $parameters); | |
while ($result != null){ | |
break; | |
} | |
} | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
return array( | |
'news/([a-z]+)/([0-9]+)' => 'news/view/$1/$2', | |
// 'news' => 'news/index', //actionIndex в NewsControle | |
// 'products' => 'product/list', //actionList в ProductController | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: Vermorr | |
* Date: 08.05.2017 | |
* Time: 16:46 | |
*/ | |
class ArticleController | |
{ | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class NewsController | |
{ | |
public function actionIndex() | |
{ | |
echo '<br><br>Список новостей'; | |
return true; | |
} | |
public function actionView($category, $id) | |
{ | |
echo 'Просмотр одной новости'; | |
return true; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: Vermorr | |
* Date: 08.05.2017 | |
* Time: 16:47 | |
*/ | |
class ProductController | |
{ | |
public function actionList() | |
{ | |
echo 'ProductController actionList'; | |
return true; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//FRONT CONTROLLER | |
// 1. Ощие настройки | |
//отбражение ошибок на время разработки | |
ini_set('display_errors', 1); | |
error_reporting(E_ALL); | |
// 2. Подключение файлов системы | |
define('ROOT', __DIR__); //определили константу ROOT | |
require_once(ROOT.'/components/Router.php'); //подключаем Роутер | |
// 3. Установка соединения с БД | |
// 4. Вызов ROUTER | |
$router = new Router(); | |
$router->run(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: Vermorr | |
* Date: 09.05.2017 | |
* Time: 13:49 | |
*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class News | |
{ | |
/* | |
* Returns single news item with specified id | |
* @param integer $id | |
* */ | |
public static function getNewsItemById($id) | |
{ | |
//Запрос к БД | |
} | |
public static function getNewsByCategory($category) | |
{ | |
//Запрос к БД | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: Vermorr | |
* Date: 09.05.2017 | |
* Time: 13:49 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment