Skip to content

Commit

Permalink
1.0.1-beta
Browse files Browse the repository at this point in the history
Mapeamento de Parâmetros e Dispatch
  • Loading branch information
KaduAmaral authored and Carlos Amaral committed Jan 3, 2017
1 parent e0fd1c7 commit 9177a46
Show file tree
Hide file tree
Showing 16 changed files with 335 additions and 160 deletions.
12 changes: 12 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,15 @@ Temporary Items
.idea/misc.xml
.idea/modules.xml
.idea/workspace.xml
/.idea/codeStyleSettings.xml
/.idea/encodings.xml
/.idea/markdown-navigator.xml
/.idea/misc.xml
/.idea/modules.xml
/.idea/vcs.xml
/.idea/workspace.xml
/.idea/copyright
/.idea/jsLinters
/.idea/markdown-navigator
/.idea/base.iml
/.idea/blade.xml
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# 1.0.1-beta

Mapeado os parâmetros da rota, com os parâmetros da _action_:

/post/:date/:slug
function postagens($slug, $date) { ... }

:date -> $date
:slug -> $slug

Passado a execução da Rota para a classe \Core\Dispatch
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Base – 1.0.0-beta
# Base – 1.0.1-beta

Base é uma "base" para construção de soluções em MVC com PHP.
Construi o _framework_ para uso próprio, porém resolvi disponibilizar
Expand Down Expand Up @@ -48,7 +48,7 @@ English
------------------------------------------------------------------------


# Base – 1.0.0-alpha.5.1.2
# Base – 1.0.1-beta

Base is a "base" for building solutions in MVC with PHP.
Build the _framework_ for their own use, but decided to make available
Expand Down
59 changes: 0 additions & 59 deletions app/example/config.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?php

use \Core\Routes\Router;
use \Core\Config;

/**
Expand All @@ -22,62 +21,4 @@
Config::Set([
'url' => 'http://localhost/Base/public_html/',
'name' => 'example',
]);

// Seta a rota de erro 404
Router::notfound([
'controller' => 'Error',
'action' => 'index'
]);


// Setá a rota padrão, home/index
Router::main([
'controller' => 'Main',
'action' => 'index'
]);

// Apenas replicando a rota padrão para ser acessada através do endereço /index
Router::route('/index', Router::main());

// Rota para o formulário de LOGIN, acessível apenas via GET
Router::get('/entrar', 'entrar', [
'controller' => 'Login',
'action' => 'index'
]);

// Replicando a rota /entrar para /login. Permitira acesso pelo mesmo Method que a rota /entrar (GET)
Router::route('/login', 'login.form', Router::GetByName('entrar')->_clone());

// Rota para realizar o login, acessível apenas via POST
Router::post('/login', 'login', [
'controller' => 'Login',
'action' => 'login'
]);


// Rota: GET /post/<id>
Router::get('/post/:id',[
'controller' => 'Main',
'action' => 'teste'
])->params([
'id' => '\d+'
]);

// Rota: GET /post/<algum-endereco>
Router::get('/post/:slug',[
'controller' => 'Main',
'action' => 'action'
])->params([
'slug' => '[a-zA-Z0-9\-_]+'
]);


// Rota: GET /post/<DD-MM-YYYY>/<algum-endereco>
Router::get('/post/:date/:slug', [
'controller' => 'Main',
'action' => 'pdate'
])->params([
'date' => '[0-9]{2}-[0-9]{2}-[0-9]{4}',
'slug' => '[a-zA-Z0-9\-_]+'
]);
5 changes: 3 additions & 2 deletions app/example/controller/maincontroller.class.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php
namespace Controller;
use Core\Request;

/**
* Main Controller
Expand All @@ -10,8 +11,8 @@ public function index(){
return $this->load->view('pages/index');
}

public function teste($id) {
return 'ID: '.$id;
public function teste($id, $nome = 'Fulano') {
return "Olá $nome, o ID é {$id}";
}


Expand Down
70 changes: 70 additions & 0 deletions app/example/routes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

use \Core\Routes\Router;

// Seta a rota de erro 404
Router::notfound([
'controller' => 'Error',
'action' => 'index'
]);


// Setá a rota padrão, home/index
Router::main([
'controller' => 'Main',
'action' => 'index'
]);

// Apenas replicando a rota padrão para ser acessada através do endereço /index
Router::route('/index', Router::main());

// Rota para o formulário de LOGIN, acessível apenas via GET
Router::get('/entrar', 'entrar', [
'controller' => 'Login',
'action' => 'index'
]);

// Replicando a rota /entrar para /login. Permitira acesso pelo mesmo Method que a rota /entrar (GET)
Router::route('/login', 'login.form', Router::GetByName('entrar')->_clone());

// Rota para realizar o login, acessível apenas via POST
Router::post('/login', 'login', [
'controller' => 'Login',
'action' => 'login'
]);


// Rota: GET /post/<id>
Router::get('/post/:id',[
'controller' => 'Main',
'action' => 'teste'
])->params([
'id' => '\d+'
]);

// Rota: GET /post/<id>
Router::get('/post/:nome/:id',[
'controller' => 'Main',
'action' => 'teste'
])->params([
'id' => '\d+',
'nome' => '\w+'
]);

// Rota: GET /post/<algum-endereco>
Router::get('/post/:slug',[
'controller' => 'Main',
'action' => 'action'
])->params([
'slug' => '[a-zA-Z0-9\-_]+'
]);


// Rota: GET /post/<DD-MM-YYYY>/<algum-endereco>
Router::get('/post/:date/:slug', [
'controller' => 'Main',
'action' => 'pdate'
])->params([
'date' => '[0-9]{2}-[0-9]{2}-[0-9]{4}',
'slug' => '[a-zA-Z0-9\-_]+'
]);
89 changes: 20 additions & 69 deletions base/core/application.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

use \Core\Request;
use \Core\Config;
use \Core\Dispatch;
use \Core\Routes\Router;
use \Core\Exception\InvalidApplicationException;
/**
Expand All @@ -12,92 +13,42 @@

class Application {

private static $config;

public static function RUN($application) {

try {
$config = Config::SetApplication($application);
self::$config = Config::SetApplication($application);

if (is_readable($config->dir . 'config.php'))
require_once $config->dir . 'config.php';
self::loadConfigs();

} catch (InvalidApplicationException $e) {
echo self::Error($e->getMessage());
return FALSE;
}

$request = Request::getInstance();

// Router em implementação
$router = Router::getInstance();

$route = $router->GetByRequest();

if ($config->onlyroutes && !$route) {
$route = Router::notfound();
}

if ($route) {
$request->controller = $route->controller;
$request->action = $route->action;
$request->params = (object) $route->attributes;
} else {
$request->parseRoute();
}

$class = "\\Controller\\{$request->controller}Controller";

// Retorno caso configuração $outputreturn do controller seja true

$output = '';

try {

if (!class_exists($class) )
throw new Exception("A URL {$request->uri} é inválida.");

$app = New $class();

} catch (Exception $e) {
echo self::Error( $e->getMessage() );
return FALSE;
}


if ( !empty($request->post['mvc:model']) ) {

$model = '\Model\\' . array_remove($request->post, 'mvc:model') . 'Model';

try {
$param = New $model($request->post);

if ($param)
$param = [$param];

} catch (Exception $e) {
$app->setOutput($app->index());
$app->output();
return FALSE;
}
} else if (!!$route && count($route->attributes) > 0)
$param = $route->attributes;
else if ( empty($request->lost) && !is_numeric($request->lost) )
$param = NULL;
else
$param = [$request->lost];

try {
$output = $app->execute($param);
} catch (Exception $e) {
Dispatch::fire();


} catch (\Exception $e) {
echo self::Error($e->getMessage());
return FALSE;
}

if ($app->outputreturn)
$app->setOutput( $output );
return TRUE;
}

private static function loadConfigs() {
$configFiles = ['config.php', 'routes.php', 'constants.php'];

$app->output();
foreach ($configFiles as $configFile)
self::loadConfigFile($configFile);
}

return TRUE;
private static function loadConfigFile($file) {
if (is_readable(self::$config->dir . $file))
require_once self::$config->dir . $file;
}


Expand Down
2 changes: 1 addition & 1 deletion base/core/config.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ public function url($value) {
if (empty($value))
throw new \InvalidArgumentException('Não é possível setar a propriedade "url" para um valor vazio.');

$this->url = $value;
$this->url = strtolower($value);
}

/**
Expand Down
46 changes: 46 additions & 0 deletions base/core/controller.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ class Controller {
*/
protected $model;

/**
* @var array
*/
protected $services = [];

/**
* @var Config
*/
Expand Down Expand Up @@ -79,6 +84,47 @@ function __construct(Request $request = NULL) {
Model::$controller = $this;
}

/**
* @param string $name
* @return Service
*/
protected function service($name, $args = []) {
if (isset($this->services[ strtolower($name) ])) return $this->services[ strtolower($name) ];

try {
$service = $this->loadClass($name, "\\Services\\", 'Service', $args);
} catch (\Exception $e) {
throw new \InvalidArgumentException('O serviço informado não existe.');
}
return $this->services[ strtolower($name) ] = $service;
}

/**
* @param string $name
* @return mixed
*/
protected function handle($name) {
$data = !empty($this->request->post[$name]) ? $this->request->post[$name] : [];
return $this->loadClass($name, "\\Model\\", "Model", $data);
}

/**
* @param string $name
* @param string $namespace
* @param string $sufix
* @param array $args
* @return mixed
*/
private function loadClass($name, $namespace = "\\", $sufix = "", $args = []) {
$class = $namespace . $name . $sufix;

if (!class_exists($class))
throw new \InvalidArgumentException('A classe informada não existe');

return new $class(...$args);
}


/**
* Executa o controlador. Em breve será papel do Dispatch
* @param mixed $param
Expand Down
Loading

0 comments on commit 9177a46

Please sign in to comment.