I need help. I am currently trying to use PHP route AltoRouter but it does not work for me. Here is my code:
require_once __DIR__ . '/vendor/autoload.php';
$router = new AltoRouter();
$router->map('GET', '/', function(){
echo 'It is working';
});
$match = $router->match();
// Here comes the new part, taken straight from the docs:
// call closure or throw 404 status
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route was matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
My browser output:
The existing list of answers I found are still not working for my code. I need help please. It's totally messing with my head.
THANK YOU VERY MUCH!
The current answers I found that did not solve for me:
PHP AltoRouter - can't get GET request
Routing via Php AltoRouter
Related
I'm using AltoRouter and works pretty well. But for every request, a new instance of AltoRouter is create and so the mapping (I followed the example from their github page).
How to avoid this overhead?
I was thinking in Singleton anti pattern. You guys think is it ok?
I have no experience with PHP.
This is code:
<?php
//begin of singleton
require 'AltoRouter.php';
$router = new AltoRouter();
$router->map('GET', '/', function () {
require '../app/home/controllers/homecontroller.php';
});
//end of singleton
$match = $router->match();
if ($match && is_callable($match['target'])) {
call_user_func_array($match['target'], $match['params']);
} else {
// no route was matched
header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
?>
My idea is to "singletonizing" the AltoRouter instance and mapping all route only once.
if you haven't used this before the link is: http://altorouter.com/
I am making a small application but do not require a framework, only the routing part. So I've decided to try altorouter out as it seemed quite simple.
I want to map certain routes to do certain things. for example:
www.example.com/products/
this should show my products.php template and pull data from the database to populate the fields. I have got this working with the following:
$router->map( 'GET', '/products', function() {
require('partials/connectdb.php'); //Require Database Connection
$pageContent = getProductsContent($conn); //prepare all the page content from database
require __DIR__ . '/products.php'; //require the template to use
});
The same for all of the other standard pages, my problem is when the route can change. For example:
www.example.com/shoes/
www.example.com/shorts/
www.example.com/shirts/
www.example.com/ties/
When a user goes to these routes I want to get the param 'shoes' and then while still using the products.php template, do the logic for only shoes.
So looking at the docs it says you can do:
www.example.com/[*] //which means anything.
However after adding this into my listed routes, it voids anything else the user trys to visit. So if they visit:
www.example.com/products // Like it worked before
It actually does the logic inside:
www.example.com/[*]
Does anyone know altorouter and can help me out please? I will paste my full page code below:
// Site Router
$router->map( 'GET', '/', function() {
require('partials/connectdb.php'); //Require Database Connection
$pageContent = getHomeContent($conn);
require __DIR__ . '/home.php';
});
$router->map( 'GET', '/products', function() {
require('partials/connectdb.php'); //Require Database Connection
$pageContent = getProductsContent($conn);
require __DIR__ . '/products.php';
});
$router->map( 'GET', '/[*]', function($id) {
require('partials/connectdb.php'); //Require Database Connection
$test = 'this was a test';
$pageContent = getProductsContent($conn);
require __DIR__ . '/products.php';
});
// match current request url
$match = $router->match();
// call closure or throw 404 status
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route was matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
Your url should be
www.example.com/products/
www.example.com/products/shoes
www.example.com/products/shirts
Then you can do this:
$router->map( 'GET', '/products/:type', function($type) {
require('partials/connectdb.php'); //Require Database Connection
if(!isset($type)){
$pageContent = getProductsContent($conn); //prepare all the page content from database
require __DIR__ . '/products.php'; //require the template to use
if($type == 'shoes'){
//do this
echo 'shoes';
}
if($type == 'shirts'){
//do that
echo 'shirts';
}
});
For some reason I am not able to start AltoRouter. I am trying the most basic call, but nothing is happening. How can I make it work?
My index.php file looks like this:
<?php
include('settings/autoload.php');
use app\AltoRouter;
$router = new AltoRouter;
$router->map('GET', '/', function(){
echo 'It is working';
});
$match = $router->match();
autoload.php:
<?php
require_once('app/Router.php');
Your Problem is that AltoRouter, according to the documentation (and in contrast to the Slim Framework, which seems to have the the same syntax), won't process the request for you, it only matches them.
So by calling $router->match() you get all the required information to process the request in any way you like.
If you just want to call the closure-function, simply modify your code:
<?php
// include AltoRouter in one of the many ways (Autoloader, composer, directly, whatever)
$router = new AltoRouter();
$router->map('GET', '/', function(){
echo 'It is working';
});
$match = $router->match();
// Here comes the new part, taken straight from the docs:
// call closure or throw 404 status
if( $match && is_callable( $match['target'] ) ) {
call_user_func_array( $match['target'], $match['params'] );
} else {
// no route was matched
header( $_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
}
And voilĂ - now you'll get your desired output!
Im using Slim Framework as an API. Im making a GET request to it. But I cannot get the headers. My PHP file looks like:
require 'Slim/Slim.php';
$app = new Slim();
$app->get('/project/:id', add_authorize(), 'getProject');
$app->run();
function getProject($project_title) {
//connect to database and return project details
}
function add_authorize() {
return function (){
$app = Slim::getInstance();
$charset = $app->request->headers->get('ACCEPT_CHARSET');
};
}
I get the response:
( ! ) Fatal error: Cannot access protected property Slim::$request in C:\wamp\www\server\device_api\index.php on line 23
Call Stack
# Time Memory Function Location
1 0.0010 248528 {main}( ) ..\index.php:0
2 0.0240 860056 Slim->run( ) ..\index.php:9
3 0.0240 878816 Slim_Route->dispatch( ) ..\Slim.php:1052
4 0.0240 878864 call_user_func:{C:\wamp\www\server\device_api\Slim\Route.php:387} ( ) ..\Route.php:387
5 0.0240 878944 {closure:C:\wamp\www\server\device_api\index.php:19-25}( ) ..\Route.php:387
I have tried absolutely everything but to no avail. I also tried getting headers directly with:
$device_id = $_SERVER['HTTP_DEVICE_ID'];
but this also failed. Any ideas how I can get a header?
Not sure if it's because of your PHP version / Slim version. This is my composer.json file:
"require": {
"slim/slim": "2.3.*"
}
I'm using PHP 5.5.14 on Mac OSX Yosemite. But anyway, try this:
// closure callback
function getProject($id)
{
// connect to database and return project details
// var_dump($id);
}
// act as a middleware, the first argument is \Slim\Route
function addAuthorize($route)
{
// var_dump($route); // \Slim\Route
$app = Slim::getInstance();
$request = $app->request();
$charset = $request->headers->get('ACCEPT_CHARSET');
}
$app->get('/project/:id', 'addAuthorize', 'getProject');
// Turn on the light
$app->run();
I suggest to do the following and not wrap things in a closure:
require 'Slim/Slim.php';
$app = new Slim();
$app->get('/project/:id', add_authorize(), 'getProject');
$app->run();
function getProject($project_title) {
//connect to database and return project details
}
function add_authorize() use ($app) {
$charset = $app->request->headers->get('ACCEPT_CHARSET');
}
The problem is that you are trying to get HTTP Headers like this
$app->request->headers->get('ACCEPT_CHARSET');
And that works after Slim version 2.x. You probably have a previous version, like 1.x.
The previous way to access the HTTP Headers was like this, without the getter:
$app->request->headers('ACCEPT_CHARSET');
You could simply change that in your code or move onto a new version of Slim.
In example here's the Slim Documentation for version 1.6.7
https://github.com/codeguy/Slim/blob/1.6.7/docs/request-headers.markdown
So after fixing mustache and Apache perms I now have ran into an issue where the site will load the index page, but any page after that located in (the same place a index.html) /pages as it fails to load.
What you can see below is the index.php for Slim to do it's stuff. I can't really understand why the index page will load just fine but no other page will load. If you can point me in the right direction then it would be greatly appreciated.
Examples:
End User > myexample.com/
Location > myexample.com/pages/index.html
The above works just fine but if you look below, you should be able to understand my issue.
End User > myexample.com/info
Location > myexample.com/pages/info.html
The End User is what you see on the site, but the location is where the files belong.
Thanks in advance, Luke.
<?php
// Load up composer autoload, and instantiate the application.
require 'vendor/autoload.php';
$app = new \Slim\Slim;
// Register a singleton of the Mustache engine, and tell it to cache
$app->container->singleton('mustache', function () {
return new Mustache_Engine(array(
'cache' => 'storage',
'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__) . '/pages', array('extension' => '.html'))
));
});
// Helper function to render templates
function renderTemplate($name, $data = array()) {
global $app;
if (file_exists('config.php')) {
$data = (require 'config.php');
}
$data += array(
'resourceUri' => $app->request->getResourceUri() ?: 'index',
'request' => $app->request
);
return $app->mustache->loadTemplate($name)->render($data);
}
// Loads a page by the given name/path
function loadPage($path) {
global $app;
// Set up the base path
$f = 'pages/' . $path;
if (file_exists($f . '.html')) {
// If there's an HTML file, render the mustache template
return renderTemplate($path . '.html');
} elseif (file_exists($f . '.php')) {
// If there's a PHP file, return it
return (require $f . '.php');
} elseif ($path != '404') {
// Otherwise, go get the 404 page
return loadPage('404');
} else {
// But if the user doesn't have a 404 page made, return a plain 404
$app->halt(404);
}
}
// Index page
$app->get('/', function () use ($app) {
echo loadPage('index');
});
// Route to everything else
$app->get('/.*?', function () use ($app) {
// Get the current request path
$path = $app->request->getResourceUri();
// Make sure the user isn't trying to escape and do nasty things
if (!preg_match('/^[A-z\/\-\_]+$/', $path)) {
echo loadPage('404');
}
// Send the page off to get loaded
echo loadPage($path);
});
$app->run();
I think you'll find your problem isn't with Slim but rather with the custom functions you wrote to allow Slim to load Mustache templates.
I would highly recommend removing those functions and using the custom Slim Mustache view provided in the views directory of Slim-Extras repo. At that point, any issues with Slim can be more easily diagnosed as there won't be custom functions to debug.
NOTE: While the Slim-Extras repo is deprecated in favor of the Slim-Views repo, the custom Mustache view (which hasn't made it to the Slim-Views repo) should work fine.
For reference please see the Custom Views section of the Slim documentation.
UPDATE: I've been using Dearon's Slim Mustache library for integration with Slim View in a new app of mine and Justin Hileman's PHP implementation of Mustache. Both are highly recommended and simple to install and configure. Good luck!