Sto cercando un modo per fornire il routing URL simile a uno in Django. Ho guardato un sacco di risorse online & Mi è piaciuto il cobweb ma il problema è che non voglio usare l'intero framework, voglio solo usare la logica di reindirizzamento URL/codice. Esiste una buona risorsa per una logica di routing URL simile a quella di Django?Routing URL simile a Django per PHP
risposta
Si potrebbe guardare CakePHP. Non so quanto sarebbe facile trascinare la logica di routing dell'URL dal resto del framework.
Non penso sia esattamente lo stesso, ma Zend Framework ha una funzionalità di routing piuttosto discendente che potreste voler vedere. Zend Framework è una specie di framework basato su componenti che non ti obbliga a utilizzare l'intera cosa. Ma penso che se si utilizza la funzionalità di routing potrebbe essere necessario utilizzare anche il loro meccanismo di controllo, poiché il router è costruito sopra.
Quello che stai cercando è un microframework. È fondamentalmente solo il livello di routing di un framework. Ce ne sono molti disponibili. Questi sembrava interessante per me:
Quello che davvero saltato la mia mente però era Silex, che si basa su Symfony2 e richiede PHP 5.3.
Avevo visto l'instradamento degli URL del framework micro PHP di Limonade e ho inviato una risposta utilizzando limonade codebase. Comunque sono tornato a guardare il codice di ragnatela ed è un po 'carino e carino. Quindi ho appena preso il routing URL di Cobweb e l'ho refactorato in OOP PHP5.x per usarlo nel mio codice.
per il confronto si veda: - http://docs.djangoproject.com/en/dev/topics/http/urls/ vs. http://www.limonade-php.net/README.htm
Le rinunce usuali sono in atto
1) non ho ancora testato tanto!
2) Esso non può avere tutte le funzionalità di routing dell'URL di Django
<?php
/**
*
* @author rajeev jha (jha dot rajeev at gmail)
* Django style URL routing.
* Pattern matching logic of this code is copied from cobweb framework
* @see http://code.google.com/p/cobweb/source/browse/trunk/dispatch/url_resolver.class.php
*
*/
class Gloo_Core_Router {
private $table ;
function __construct() {
//initialize routing table
$this->table = new Gloo_Core_RoutingTable();
}
function getRoute($path,$domain=NULL){
if(empty($path)) {
$message = sprintf("Please supply a valid path to match :: got [%s] ", $path);
trigger_error($message,E_USER_ERROR);
}
//all rules for this domain
$rules = $this->table->getRules($domain);
$route = NULL ;
if($path == '/')
$route = $this->matchHome($rules);
else
$route = $this->match($rules,$path);
return $route ;
}
private function matchHome($rules) {
$route = NULL ;
foreach($rules as $rule) {
if($rule["pattern"] == '/') {
$route = $this->createRoute($rule,array());
}
}
return $route ;
}
private function match($rules,$path) {
$path = ltrim($path, '/');
$matches = array();
$route = NULL ;
foreach($rules as $rule) {
if(preg_match($this->patternize($rule["pattern"]),$path,$matches) != 0) {
//match happened
$matches = $this->sanitizeMatches($matches);
$route = $this->createRoute($rule,$matches);
}
}
return $route ;
}
private function createRoute($rule,$matches) {
$route = $rule ;
//add parameters
$route["params"] = $matches ;
return $route ;
}
private function sanitizeMatches($matches){
//discard the first one
if (count($matches) >= 1)
$matches = array_splice($matches,1);
$unset_next = false;
//group name match will create a string key as well as int key
// like match["token"] = soemthing and match[1] = something
// remove int key when string key is present for same value
foreach ($matches as $key => $value) {
if (is_string($key)){
$unset_next = true;
} else if (is_int($key) && $unset_next) {
unset($matches[$key]);
$unset_next = false;
}
}
return array_merge($matches);
}
private function patternize($pattern) {
//http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
//treat pattern as UTF-8
return '{'.$pattern.'}u' ;
}
}
?>
<?php
/**
*
* @author rajeev jha (jha dot rajeev at gmail)
* Django style URL routing.
* URL routing table
*
*/
class Gloo_Core_RoutingTable {
private $rules ;
private $splrules ;
const ANY_DOMAIN = '__ANY__' ;
function __construct() {
$this->rules = array();
$this->splrules = array();
//@todo inject from outside
$this->createRule(self::ANY_DOMAIN, '/', 'Gloo_Controller_Home');
//match alphanumeric + dashes
//a pcre word (\w) does not contain dashes
$this->createRule(self::ANY_DOMAIN, '^(?P<token>[-\w]+)$','Gloo_Controller_Post');
$this->createRule(self::ANY_DOMAIN, '^page/(?P<pagenum>\d+)$','Gloo_Controller_Home');
$this->createRule(self::ANY_DOMAIN, '^(?P<token>\w+)/page/(?P<pagenum>\d+)$','Gloo_Controller_Post');
$this->createRule(self::ANY_DOMAIN, '^category/(?P<name>\w+)$','Gloo_Controller_Category');
$this->createRule(self::ANY_DOMAIN, '^category/(?P<name>\w+)/page/(?P<pagenum>\d+)$','Gloo_Controller_Category');
//special rules
$this->createRule('www.test1.com','^(?P<token>\w+)$','Gloo_Controller_File', array("template" => "post.php"));
}
function createRule($domain,$pattern,$action,$options=NULL) {
if(empty($domain)) {
trigger_error("No domain supplied for rule" ,E_USER_ERROR);
}
$rule = array();
$rule["pattern"] = $pattern;
$rule["action"] = $action ;
//Add options
if(is_null($options))
$rule["options"] = array();
else
$rule["options"] = $options ;
$rule["domain"] = $domain ;
//add to generic or domain specific rules
if($domain == self::ANY_DOMAIN)
$this->rules[] = $rule ;
else
$this->splrules[$domain][] = $rule ;
}
function getRules($domain) {
if(empty($domain))
return $this->rules ;
//valid domain - rules as well
// add to existing rules
if(array_key_exists($domain,$this->splrules)) {
$splrules = $this->splrules[$domain];
$rules = array_merge($this->rules,$splrules);
return $rules ;
} else {
return $this->rules ;
}
}
}
?>
Ora, è possibile aggiungere tutte le regole per l'inizializzazione della tabella di routing. a seconda del dominio + "percorso" che fornisci al router, la stringa "controller" viene ripristinata insieme ai parametri "gruppo denominato" e ad altri parametri corrispondenti. Non sto includendo la logica di istanza di classe per le stringhe "controller" perché 1) che sarebbe complicato 2) Se la tua intenzione è di ottenere solo un routing URL come Django, questo è abbastanza buono.
Riferimenti
codice Limonade è qui: - https://github.com/sofadesign/limonade/blob/master/lib/limonade.php
codice ragnatela è qui: - http://code.google.com/p/cobweb/source/browse/trunk/dispatch/url_resolver.class.php
- il mio codice è qui: - https://code.google.com/p/webgloo/source/browse/trunk/php/lib/Gloo/Core/Router.php
- vecchia versione del mio codice: - quello che ho modificato qui - era basato su limonade ed era piuttosto danneggiato al cervello. Sentiti libero di guardare il link Limonade sopra. Lo sto rimuovendo.
Uso
$ router = new Gloo_Core_Router();
$path = 'category/news/page/3' ;
printf("Now matching path [%s]" , $path);
$route = $router->getRoute($path);
print_r($route);
$path = '/category/Health/page' ;
printf("Now matching path [%s]" , $path);
$route = $router->getRoute($path);
print_r($route);
Devi cambiare i nomi di classe e comprendono le dipendenze ma hey, sei un programmatore; D
ho sviluppato un quadro simile con CodeIgniter e Django risorse, http://williamborba.github.io/willer/quick_start/
E 'ancora in fase beta , ma sto gradualmente implementando e migliorando il file URL.php è molto simile a URLS.py django.
Un altro punto saliente sono i modelli e l'ORM molto simile al django, ma con qualcosa di simile al record attivo del codeigniter.
- 1. Url routing regex PHP
- 2. Schema URL simile a Gmail
- 3. Modello quadro simile a Django
- 4. AngularJS: parametri URL per il routing
- 5. : URL simile utilizzando JavaScript
- 6. Symfony2 traduce URL e routing
- 7. ASP.NET MVC routing/SEO friendly URL
- 8. Django url debugger
- 9. Qualcosa di simile a Hibernate in PHP?
- 10. Framework PHP simile a Python Pylons
- 11. Quale framework PHP è più simile a Ruby on Rails?
- 12. Analogo PHP di funzione simile a mysql
- 13. Django & Celery - Problemi di routing
- 14. Esiste una funzione simile a setTimeout() (JavaScript) per PHP?
- 15. Esiste qualcosa di simile a "rake routes" in django?
- 16. Django modello url per% 20
- 17. Url di routing in lettere minuscole come?
- 18. Routing URL per stati nidificati in ui-router
- 19. Rails 3.2 amichevole url di routing per data
- 20. Più URL di routing per singolo servizio AngularJS
- 21. Django: Best Practice per URL conf, url modello tag
- 22. ASP.NET MVC: routing url vs querystring
- 23. .NET MVC routing w/URL Encoding Problemi
- 24. Routing in Rails. Dots in URL
- 25. Percorso URL inverso JS espresso (stile Django)
- 26. MVC routing sbarazzarsi di/Indice in URL
- 27. Routing vs Url Rewrite (IIS7) Prestazioni
- 28. API di database astratta simile a Django per progetti non-Django
- 29. Django: prefisso URL a livello di sito
- 30. Django cross-site URL
Hmm.ok. Speravo di evitare l'uso del controller. – Chantz