Returning Route Parameter in a page in SLIM 3 - slim

i a, having a link which sends public to view timeline of a specific user by passing variable in route.
<a href="<?php echo $baseLocation ?>/bnb-details/<?php echo $row['username']?>" >View</a>
and my route is defined as:
$app->get('/bnb-details/{name}', function (Request $request, Response $response, $args) {
include_once('bnb-details.php');
return $response; });
how can i pass the {name} args in the bnb-details.php ??
any kind of help would be appriciated.

you can use like this :
you should pass parametere from args to variable
$app->get('/bnb-details/{name}', function (\Slim\Http\Request $request, \Slim\Http\Response $response, $args) {
$name = $args['name'];
include_once('bnb-details.php');
return $response;
});
then use
echo $name;
in bnb-details.php

Related

Slim 4 get all routes into a controller without $app

I need to get all registed routes to work with into a controller.
In slim 3 it was possible to get the router with
$router = $container->get('router');
$routes = $router->getRoutes();
With $app it is easy $routes = $app->getRouteCollector()->getRoutes();
Any ideas?
If you use PHP-DI you could add a container definition and inject the object via constructor injection.
Example:
<?php
// config/container.php
use Slim\App;
use Slim\Factory\AppFactory;
use Slim\Interfaces\RouteCollectorInterface;
// ...
return [
App::class => function (ContainerInterface $container) {
AppFactory::setContainer($container);
return AppFactory::create();
},
RouteCollectorInterface::class => function (ContainerInterface $container) {
return $container->get(App::class)->getRouteCollector();
},
// ...
];
The action class:
<?php
namespace App\Action\Home;
use Psr\Http\Message\ResponseInterface;
use Slim\Http\Response;
use Slim\Http\ServerRequest;
use Slim\Interfaces\RouteCollectorInterface;
final class HomeAction
{
/**
* #var RouteCollectorInterface
*/
private $routeCollector;
public function __construct(RouteCollectorInterface $routeCollector)
{
$this->routeCollector = $routeCollector;
}
public function __invoke(ServerRequest $request, Response $response): ResponseInterface
{
$routes = $this->routeCollector->getRoutes();
// ...
}
}
This will display basic information about all routes in your app in SlimPHP 4:
$app->get('/tests/get-routes/', function ($request, $response, $args) use ($app) {
$routes = $app->getRouteCollector()->getRoutes();
foreach ($routes as $route) {
echo $route->getIdentifier() . " → ";
echo ($route->getName() ?? "(unnamed)") . " → ";
echo $route->getPattern();
echo "<br><br>";
}
return $response;
});
From there, one can use something like this to get the URL for a given route:
$routeParser = \Slim\Routing\RouteContext::fromRequest($request)->getRouteParser();
$path = $routeParser->urlFor($nameofroute, $data, $queryParams);
With the following caveats:
this will only work for named routes;
this will only work if the required route parameters are provided -- and there's no method to check whether a route takes mandatory or optional route parameters.
there's no method to get the URL for an unnamed route.

GET url parameters Codeigniter

There is one view, and one controller, it is necessary, with the use of the get parameter, to change the path by the link. So in the end it turned out like this:
Upcoming -> http://mywebsite.com/tournaments?type=upcoming
Finished -> http://mywebsite.com/tournaments?type=finished
Here is the controller which will process your GET variable
Controller
<?php
class Demo_controller extends CI_Controller
{
public function demo($id)
{
echo $id; //the id which you will get in URL string
}
}
?>
View File where you will pass the Variable
<?php
$id = "1";//dyanmic id which will be pased with the form
echo form_open('demo/demos-function'.$id);
//in between your code
echo form_close
?>
Routes
Inside routes.php
$route['demo/demos-function/(:any)] = Demo_controller/demo/$1
No need to change the $1 it will explain the routes that it is having URL paramater.
So Ultimately Your link will be
https://localhost/demo/demos-function/1
https://localhost/demo/demos-function/2
In Codeigniter Url like this :
Upcoming -> http://mywebsite.com/controller/method/upcoming
Finished -> http://mywebsite.com/controller/method/finished
public function method_name()
{
$type = $this->uri->segment(3); // third level value of URL - Segment(1) is controller and followed by method and query string
if($type == 'upcoming')
{
echo $type;
$this->load->view('upcoming');
}
else
{
echo $type;
$this->load->view('finished');
}
}

Slim 3 - replacement for isPost()?

In Slim 2, I would do this,
$app->map('/login', function () use ($app) {
// Test for Post & make a cheap security check, to get avoid from bots
if ($app->request()->isPost() && sizeof($app->request()->post()) >= 2) {
//
}
// render login
$app->render('login.twig');
})->via('GET','POST')->setName('login');
But in Slim 3,
// Post the login form.
$app->post('/login', function (Request $request, Response $response, array $args) {
// Get all post parameters:
$allPostPutVars = $request->getParsedBody();
// Test for Post & make a cheap security check, to get avoid from bots
if ($request()->isPost() && sizeof($allPostPutVars) >= 2) {
///
}
});
I get this error,
Fatal error: Function name must be a string in C:...
Obviously that isPost() is deprecated, so what should I use instead in Slim 3 for isPost's replacement?
In Slim 4, there's no such helper and so the syntax gets longer (like a lot of Slim 4 stuff):
$request->getMethod() === 'POST'
According to documentation and comments, Slim supports these proprietary methods:
$request->isGet()
$request->isPost()
$request->isPut()
$request->isDelete()
$request->isHead()
$request->isPatch()
$request->isOptions()
Here it is an example of usage:
<?php
require 'vendor/autoload.php';
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
$app = new \Slim\App;
$app->map(['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'PATCH', 'OPTIONS'], '/', function (ServerRequestInterface $request, ResponseInterface $response) {
echo "isGet():" . $request->isGet() . "<br/>";
echo "isPost():" . $request->isPost() . "<br/>";
echo "isPut():" . $request->isPut() . "<br/>";
echo "isDelete():" . $request->isDelete() . "<br/>";
echo "isHead():" . $request->isHead() . "<br/>";
echo "isPatch():" . $request->isPatch() . "<br/>";
echo "isOptions():" . $request->isOptions() . "<br/>";
return $response;
});
$app->run();

Test a REST get request

How do I test a GET request of a REST API with PHPUnit 4.1? I use the Slim PHP-Framework and could manage to test the response code but not the body or header.
This is what I have so far:
TestClass:
class AssetTest extends PHPUnit_Framework_TestCase
{
public function request($method, $path, $options = array())
{
// Capture STDOUT
ob_start();
// Prepare a mock environment
Environment::mock(array_merge(array(
'REQUEST_METHOD' => $method,
'PATH_INFO' => $path,
'SERVER_NAME' => 'slim-test.dev',
), $options));
$app = new \Slim\Slim();
$this->app = $app;
$this->request = $app->request();
$this->response = $app->response();
// Return STDOUT
return ob_get_clean();
}
public function get($path, $options = array()){
$this->request('GET', $path, $options);
}
public function testGetAssets(){
$this->get('/asset');
$this->assertEquals('200', $this->response->status());
}
}
If my JSON response of http://example.com/asset looks like this (Code 200):
[
{
"AssetID": "4b0be88b9e853",
"AssetStatusID": "1"
}
]
Everything is good. To get the body of response just call the
$response->getBody() and use json_decode to decode this response. To get the header call the $response->getHeaders().
In your case it will by $this->response->getBody(). So your test
method will be look like this
public function testGetAssets(){
$this->get('/asset');
$response = json_decode($this->response->getBody(), true); //response body
$headers = $this->response->getHeaders() //response headers
$this->assertEquals('200', $this->response->status());
}
This answer is respect to the latest version of guzzlehttp i.e. 6.0

Sending a SOAP message with PHP

what I'm trying to do is send a load of values captured from a form to a CRM system with SOAP and PHP. I've been reading up on SOAP for a while and I don't understand how to go about doing so, does anybody else know?
In order to do this it might be easiest to download a simple soap toolkit like 'NuSOAP' from sourceforge.
And then you would code something like the following (example submission of ISBN number):
<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
print "Error: ". $fault;
}
else if ($price == -1) {
print "The book is not in the database.";
} else {
// otherwise output the result
print "The price of book number ". $param[isbn] ." is $". $price;
}
// kill object
unset($client);
?>
This code snippet was taken directly from, which is also a good resource to view
http://developer.apple.com/internet/webservices/soapphp.html
Hope this helps.
You probably found a solution since then - but maybe the following helps someone else browsing for this:
soap-server.php:
<?php
class MySoapServer {
public function getMessage ()
{
return "Hello world!";
}
public function add ($n1,$n2)
{
return $n1+n2;
}
}
$option = array ('uri' => 'http://example.org/stacky/soap-server');
$server = new SoapServer(null,$option);
$server->setClass('MySoapServer');
$server->handle();
?>
and soap-client.php
<?php
$options = array ('uri' => 'http://example.org/stacky/soap-server',
'location' => 'http://localhost/soap-server.php');
$client = new SoapClient(null,$options);
echo $client ->getMessage();
echo "<br>";
echo $client ->add(41,1);
?>