1. Go to this page and download the library: Download vladdyslav/klein-up library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
vladdyslav / klein-up example snippets
in = new \Klein\Klein();
$klein->respond('GET', '/hello-world', function () {
return 'Hello World!';
});
$klein->dispatch();
$klein->respond(function () {
return 'All the things';
});
$klein->respond('/[:name]', function ($request) {
return 'Hello ' . $request->name;
});
$klein->respond('GET', '/posts', $callback);
$klein->respond('POST', '/posts', $callback);
$klein->respond('PUT', '/posts/[i:id]', $callback);
$klein->respond('DELETE', '/posts/[i:id]', $callback);
$klein->respond('OPTIONS', null, $callback);
// To match multiple request methods:
$klein->respond(array('POST','GET'), $route, $callback);
// Or you might want to handle the requests in the same place
$klein->respond('/posts/[create|edit:action]?/[i:id]?', function ($request, $response) {
switch ($request->action) {
//
}
});
$klein->respond(function ($request, $response, $service) {
$service->xml = function ($object) {
// Custom xml output function
}
$service->csv = function ($object) {
// Custom csv output function
}
});
$klein->respond('/report.[xml|csv|json:format]?', function ($request, $response, $service) {
// Get the format or fallback to JSON as the default
$send = $request->param('format', 'json');
$response->$send($report);
});
$klein->respond('/report/latest', function ($request, $response, $service) {
$response->file('/tmp/cached_report.zip');
});
$klein->respond(function ($request, $response, $service, $app) use ($klein) {
// Handle exceptions => flash the message and redirect to the referrer
$klein->onError(function ($klein, $err_msg) {
$klein->service()->flash($err_msg);
$klein->service()->back();
});
// The fourth parameter can be used to share scope and global objects
$app->db = new PDO(...);
// $app also can store lazy services, e.g. if you don't want to
// instantiate a database connection on every response
$app->register('db', function() {
return new PDO(...);
});
});
$klein->respond('POST', '/users/[i:id]/edit', function ($request, $response, $service, $app) {
// Quickly validate input parameters
$service->validateParam('username', 'Please enter a valid username')->isLen(5, 64)->isChars('a-zA-Z0-9-');
$service->validateParam('password')->notNull();
$app->db->query(...); // etc.
// Add view properties and helper methods
$service->title = 'foo';
$service->escape = function ($str) {
return htmlentities($str); // Assign view helpers
};
$service->render('myview.phtml');
});
// myview.phtml:
<title> echo $this->escape($this->title)
$klein->with('/users', function () use ($klein) {
$klein->respond('GET', '/?', function ($request, $response) {
// Show all users
});
$klein->respond('GET', '/[:id]', function ($request, $response) {
// Show a single user
});
});
foreach(array('projects', 'posts') as $controller) {
// Include all routes defined in a file under a given namespace
$klein->with("/$controller", "controllers/$controller.php");
}
// Routes to "/projects/?"
$this->respond('GET', '/?', function ($request, $response) {
// Show all projects
});
$service->addValidator('hex', function ($str) {
return preg_match('/^[0-9a-f]++$/i', $str);
});
$service->validateParam('key')->isHex();
$service->validate($username)->isLen(4,16);
$service->validateParam('key', 'The key was invalid')->isHex()->isLen(32);
$klein->respond('*', function ($request, $response, $service) { $service->render('header.phtml'); });
//other routes
$klein->respond('*', function ($request, $response, $service) { $service->render('footer.phtml'); });
// Match all requests that end with '.json' or '.csv'
$klein->respond('@\.(json|csv)$', ...
// Match all requests that _don't_ start with /admin
$klein->respond('!@^/admin/', ...
$service->escape = function ($str) {
return htmlentities($str);
};
$service->render('myview.phtml', array('title' => 'My View'));
// Or just: $service->title = 'My View';
$this->render('partial.html') // Render partials
$this->sharedData()->get('myvar') // Access stored service variables
echo $this->query(array('page' => 2)) // Modify the current query string
$request->
id($hash = true) // Get a unique ID for the request
paramsGet() // Return the GET parameter collection
paramsPost() // Return the POST parameter collection
paramsNamed() // Return the named parameter collection
cookies() // Return the cookies collection
server() // Return the server collection
headers() // Return the headers collection
files() // Return the files collection
body() // Get the request body
params() // Return all parameters
params($mask = null) // Return all parameters that match the mask array - extract() friendly
param($key, $default = null) // Get a request parameter (get, post, named)
isSecure() // Was the request sent via HTTPS?
ip() // Get the request IP
userAgent() // Get the request user agent
uri() // Get the request URI
pathname() // Get the request pathname
method() // Get the request method
method($method) // Check if the request method is $method, i.e. method('post') => true
query($key, $value = null) // Get, add to, or modify the current query string
<param> // Get / Set (if assigned a value) a request parameter
$response->
protocolVersion($protocol_version = null) // Get the protocol version, or set it to the passed value
body($body = null) // Get the response body's content, or set it to the passed value
status() // Get the response's status object
headers() // Return the headers collection
cookies() // Return the cookies collection
code($code = null) // Return the HTTP response code, or set it to the passed value
prepend($content) // Prepend a string to the response body
append($content) // Append a string to the response body
isLocked() // Check if the response is locked
cope of $response)
addValidator($method, $callback) // Add a custom validator method
validate($string, $err = null) // Validate a string (with a custom error message)
validateParam($param, $err = null) // Validate a param
<callback>($arg1, ...) // Call a user-defined helper
<property> // Get a user-defined property
$app->
<callback>($arg1, ...) //Call a user-defined helper
$validator->
notNull() // The string must not be null
isLen($length) // The string must be the exact length
isLen($min, $max) // The string must be between $min and $max length (inclusive)
isInt() // Check for a valid integer
isFloat() // Check for a valid float/decimal
isEmail() // Check for a valid email
isUrl() // Check for a valid URL
isIp() // Check for a valid IP
isAlpha() // Check for a-z (case insensitive)
isAlnum() // Check for alphanumeric characters
contains($needle) // Check if the string contains $needle
isChars($chars) // Validate against a character list
isRegex($pattern, $modifiers = '') // Validate against a regular expression
notRegex($pattern, $modifiers ='')
is<Validator>() // Validate against a custom validator
not<Validator>() // The validator can't match
<Validator>() // Alias for is<Validator>()
php
$klein->respond(function ($request, $response, $service, $app) {
$app->register('lazyDb', function() {
$db = new stdClass();
$db->name = 'foo';
return $db;
});
});
//Later
$klein->respond('GET', '/posts', function ($request, $response, $service, $app) {
// $db is initialised on first request
// all subsequent calls will use the same instance
return $app->lazyDb->name;
});
html
<title> echo $this->escape($this->title)
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.