Giter Site home page Giter Site logo

slimphp / slim Goto Github PK

View Code? Open in Web Editor NEW
11.8K 504.0 1.9K 7.04 MB

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.

Home Page: http://slimframework.com

License: MIT License

PHP 100.00%
slim slim-framework php php-micro-framework framework micro-framework psr-7 psr-15 psr-3

slim's Introduction

Slim Framework

Build Status Coverage Status Total Downloads License

Slim is a PHP micro-framework that helps you quickly write simple yet powerful web applications and APIs.

Installation

It's recommended that you use Composer to install Slim.

$ composer require slim/slim

This will install Slim and all required dependencies. Slim requires PHP 7.4 or newer.

Choose a PSR-7 Implementation & ServerRequest Creator

Before you can get up and running with Slim you will need to choose a PSR-7 implementation that best fits your application. A few notable ones:

Slim-Http Decorators

Slim-Http is a set of decorators for any PSR-7 implementation that we recommend is used with Slim Framework. To install the Slim-Http library simply run the following command:

composer require slim/http

The ServerRequest and Response object decorators are automatically detected and applied by the internal factories. If you have installed Slim-Http and wish to turn off automatic object decoration then you can use the following statements:

<?php

use Slim\Factory\AppFactory;
use Slim\Factory\ServerRequestCreatorFactory;

AppFactory::setSlimHttpDecoratorsAutomaticDetection(false);
ServerRequestCreatorFactory::setSlimHttpDecoratorsAutomaticDetection(false);

$app = AppFactory::create();

// ...

Hello World using AppFactory with PSR-7 auto-detection

In order for auto-detection to work and enable you to use AppFactory::create() and App::run() without having to manually create a ServerRequest you need to install one of the following implementations:

Then create file public/index.php.

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

// Instantiate App
$app = AppFactory::create();

// Add error middleware
$app->addErrorMiddleware(true, true, true);

// Add routes
$app->get('/', function (Request $request, Response $response) {
    $response->getBody()->write('<a href="/hello/world">Try /hello/world</a>');
    return $response;
});

$app->get('/hello/{name}', function (Request $request, Response $response, $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
});

$app->run();

You may quickly test this using the built-in PHP server:

$ php -S localhost:8000 -t public

Going to http://localhost:8000/hello/world will now display "Hello, world".

For more information on how to configure your web server, see the Documentation.

Tests

To execute the test suite, you'll need to install all development dependencies.

$ git clone https://github.com/slimphp/Slim
$ composer install
$ composer test

Contributing

Please see CONTRIBUTING for details.

Learn More

Learn more at these links:

Security

If you discover security related issues, please email [email protected] instead of using the issue tracker.

For enterprise

Available as part of the Tidelift Subscription.

The maintainers of Slim and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Contributors

Code Contributors

This project exists thanks to all the people who contribute. Contribute.

Financial Contributors

Become a financial contributor and help us sustain our community. Contribute

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. Contribute

License

The Slim Framework is licensed under the MIT license. See License File for more information.

slim's People

Contributors

adriansuter avatar adriencarbonne avatar akrabat avatar ashleycoles avatar bnf avatar bobdia avatar briannesbitt avatar codeguy avatar dependabot-preview[bot] avatar dependabot[bot] avatar designermonkey avatar dopesong avatar geggleto avatar gmanricks avatar joebengalen avatar jwpage avatar l0gicgate avatar lalop avatar llvdl avatar mapogolions avatar mathmarques avatar mehdihasanpour avatar micheh avatar nbayramberdiyev avatar opengeek avatar pine3ree avatar rotzbua avatar sam-burns avatar silentworks avatar t0mmy742 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

slim's Issues

register_shutdown_function causing problems with exceptions

Although the approach of using register_shutdown_function('Slim::run'); to avoid explicitly calling the run method saves a little typing, it causes problems when your application throws an exception:

Fatal error: Exception thrown without a stack frame in Unknown on line 0

Two suggestions:

  1. Short term: make the call to Slim::run() explicit, at the bottom of the bootstrap.php file. Yes, it's slightly more typing, but using register_shutdown_function will cause lots of problems with exceptions. Also, it creates a point at which the behaviour of Slim cannot be overridden. Once a shutdown function is registered it can't be unregistered. This causes a few painful issues in Kohana which we want to avoid.
  2. A longer-term solution (for the roadmap): Slim probably needs a try/catch block around the code in the run method. If an exception bubbles up to the top here, Slim should return a 500 error code and display a graceful error page (perhaps it should only do this in production mode, and display the full error message in development mode).

Optional route segments with default argument values

We need a clean and simple method to define default values for route parameters. I am opening this for discussion only for now because this may require larger changes to routing code, and I would like to settle on a plan of attack before moving to code. Post your thoughts here.

MustacheView not rendering

I've just updated to the develop branch, and I can't get the MustacheView to render anything. I've isolated an ad-hoc test case (http://dpaste.com/hold/280035/), it just renders a blank page, nothing gets printed in apache's log or anywhere visible.

Using config('debug', true), and Slim::log() makes no difference.

Improve Error and Exception Handling

Create a generic SlimException sub-class of Exception. This Exception should be used for:

  • Slim::error
  • Slim::redirect
  • Arbitrary exceptions

The Slim::run method will have a try/catch block which will catch any thrown Exceptions and use the Exception status code to set the HTTP status code, and the Exception message as the response body.

Also, I may change Slim::error to Slim::raise( message, status = 500 ) since this feature may be used for more than just "errors".

plugin access rights

the plugin example from the docu states:

$currentRoute = Slim::router()->current();

if ( preg_match('@^users/@', $currentRoute->pattern) ) {

result here is:
PHP Fatal error: Cannot access private property Route::$pattern

Problem with Windows

Request::extractQueryString creates incorrect $root on Windows

From user:

I have figured out the root cause the problem I saw. It is from $request->$root.

private function extractQueryString() {
    $this->root = rtrim(dirname($_SERVER['PHP_SELF']), '/') . '/';
    $uri = ltrim(preg_replace('@' . preg_quote($this->root, '@') . '@', '', $_SERVER['REQUEST_URI'], 1), '/');
    $questionMarkPosition = strpos($uri, '?');
    if ( !!$questionMarkPosition ) {
        return substr($uri, 0, $questionMarkPosition);
    }
    return $uri;
}

I run on Windows box, so dirname($_SERVER['PHP_SELF']); gives ''. I guess we can use conditional statement to resolve this. I would want you to try the highlighted code on Windows first before confirming my findings. I use Slim Version 1.0, being lazy I downloaded from your site.

Now, I will start working on including SQL however rudimentary.

Something's wrong with Slim::halt()?

I'm using one line of Code which looks like this:
$link = mysql_connect(Slim::config('mysqlserver'), Slim::config('mysqluser'), Slim::config('mysqlpassword')) or Slim::halt(500, 'Cannot Connect to Database Server.');

Now my MySQL Server is not running currently. So it should raise an error 500 containing my Message. But this does not happen.

Instead I get the following: Fatal error: Exception thrown without a stack frame in Unknown on line 0

When starting my MySQL Server the error is gone. So my code should actually be fine.

I'm running PHP 5.3.3 as CGI.

Implement Slim::config('name', 'value')

Implement Slim app-wide settings with a controlled-vocabulary for certain settings (ie. templates, mode, debug, etc) but also allowing user-specific settings.

Add urlFor helper method

This method is already available in the Router, but to lessen the amount of typing, I would like to add this to the Slim class, as well. So now you only need to call Slim::urlFor() rather than Slim::router()->urlFor().

Add Pass helper method

Add Pass helper method to Slim class that throws a specifc Exception (may require sub-classing Exception). This specific class of Exception should be caught in the Dispatch Loop, and if caught, should cause the Dispatch Loop to continue to the next matching Route. May require refactoring of Slim::run.

Add Redirect helper method

Add redirect helper method to Slim class. This method should set Location: header and the status code (which defaults to 302). An alternate status may be set, but it must be a valid status code to be set.

Default Parameters for Routes

Just an Idea - may be this is one of those 20% of what you call edge use cases:
When defining a Route (Slim::get(nickinfo/:nick/:format) which has to get two parameters ('nick' and 'format' in this case) but those or a single one are not set, I'm getting a 404 by default.

Now when adding some 'predefined defaults' for those 2 parameters wouldn't generate a 404 but makes the Application return proper results.

Slim Hooks and Slim Filters

I noticed that Slim::hook() passes self:$app to listeners as the only argument. Also, the example hook callbacks in the wiki don't define any arguments. So, I'm thinking that maybe hooks should use Slim::getInstance() instead.

On another note, listeners are invoked like this:
foreach( self::$app->hooks[$name] as $listener )
$listener(self::$app);

We should definitely change that to:

call_user_func($listener, self::$app);

which is the correct way to invoke callables.

I've forked Slim and fixed this along with implementing filters as a companion to hooks.

Example:
// set up a filter
Slim::filter('html', function ($var) {
return strip_tags($var);
});

// ... and later apply the filters
echo Slim::applyFilter('html', $html);

I will push my "filter_hooks" branch to Github later today. Let me know what you think.

Stripslashes

Hello World` application (PHP 5 < 5.3)

So you're supporting less than 5.3 in some cases s I thought I'd mention this bug.

You need to stripslashes if get_magic_quotes_gpc is enabled. I used an array_map and static function to remove them recursively and call it on $COOKIE, $_POST and $_GET.

    public static function stripslashes($value) {
            if (is_array($value)) {
                    $value = array_map(array('CLASSNAME', 'stripslashes'), $value);
            } else {
                    $value = stripslashes($value);
            }
            return $value;
    }

trailing slashes on routes

Don't know how to describe this correctly, but a route /nickinfo/ is not the same as /nickinfo - which actually makes no sense in case a route does not require any parameters.

Let's think about the following: A route is created like Slim::get('foo/', $callback) someone enteres a URL into a Browser to http://whatever/foo he'll get a 404, http://whatever/foo/on the other hand works. This should behave the same for trailing slashes. The same is for routes with parameters (e.g. http://whatever/foo/:one/:two/)

I of course have to say, that I'm not using the 'original' .htaccess as i really don't need a suffix '.html' for each request since I primary using json, xml or plain text as output format.

Create SmartyView

Create SmartyView custom View class. I'm working on this now and should have it wrapped up by this weekend.

defaultNotFound

The default 404 handler does not work in Google Chrome. According to this link, 404 pages must be at least 512 bytes long for Chrome to display them.

Also, the default 404 is a bit ugly. Why don't we generalise the generateErrorMarkup method to display any type of error, including 404s? We could (for example) show the routes matched, in order. We could pad the content with ย  to ensure it reaches 513 bytes.

Indentation problems

There seem to be some indentation issues creeping in - see this comment block for example.

The problems are:

  1. Most lines are indented with tabs, but some are indented with spaces.
  2. Blank lines often have a single tab character on them. This is a bit messy.

This should probably be fixed sooner rather than later. Pick a style (most of Slim already uses tabs, so I would recommend sticking with tabs for minimal disruption). Fix all the Slim files (normalise indentation and remove hanging indentation on blank lines). Then document in the wiki the indentation style for all contributors. Check all patches conform to this style.

I am happy to do this work, but I'll wait for a decision on which style you want to go with.

$this-root not valid on Windows Machines

on 203 line in Request.php used

203: $this->root = ltrim(dirname($_SERVER['PHP_SELF']), '/') . DIRECTORY_SEPARATOR;

so for windows machine it append with symbol: '' instead '/'

in URI used only '/' as separator, thats why little fix is:

203: $this->root = ltrim(dirname($_SERVER['PHP_SELF']), '/') . '/';

and needed to find other places where user DIRECTORY_SEPARATOR in such cases.

Thanks,
Paul

[Develop Branch] Optional route segments break automatic trailing slash

The (awesome) optional route segments in the develop branch confound the automatic trailing slash rewrite. e.g.:

 Slim::get('/maintenance/(:time)', function ( $time = "a while" ) {
Slim::render('50x.php', array( 'time' => $time ) );
 });

 Slim::get('/login/(:msg)', function( $msg = null ) {
Slim::render('form-login.php');
 });

For the first, if I want to say, "Come back in an hour" I set the URI to /maintenance/in%20an%20hour. However, the optional segment for both '/maintenance/' and '/login/' throw 404s without the trailing slash 100% of the time; perhaps it's the regex?

Rename Slim::raise to Slim::halt

I think this is more semantic and indicative of the purpose of this method. Slim::raise implies more of a negative connotation relating to "raising" an exception, when in fact this method is used to halt the progress of the application and immediately return a custom status code and body message.

isAjax won't return true even if HTTP Header "X-Requested-With" is set to "XMLHttpRequest"

I'm not totally sure, if this is an Issue really or if here's going something wrong, but I'm POSTing data to Route using a jQuery.ajax call. For debugging I added an Output-Field which should contain "Slim::request()->isAjax;". This unfortunately is always set to "false".

Firebug anyway tells me that the Request Header Field "X-Requested-With" is set to "XMLHttpRequest" so it should be recognized as Ajax-Call.

for the records: I'm on 5.2.6 via apache2 on that machine but happens on my usual nginx, php 5.3.3 via fastcgi as well.

Instantiate View class on Slim construct

Set the default View on Slim __construct so that we can set individual View data before Slim::render is called. Should a user set a custom view during __construct or later on, it is important that any existing data in the default View be transferred to the new View object.

Django/Rack-inspired Error Page?

Especially with REST mapping like Slim has, and well documented exceptions to play with, a graceful error page might be a decent addition.

Obviously PHP doesn't support stack tracing out of the box in error handling, and I couldn't possibly imagine trying to add in a meaningful parser for a cachegrind file from XDebug that would n't be bloated as all get out.

Thoughts? Been toying with the idea the past couple hours.

e.g. (in ruby)
https://github.com/rack/rack/blob/master/lib/rack/showexceptions.rb

$this->cookies in Response not persisting

The cookies added to the (response) $this->cookies[] array, for some reason, aren't making it to ln. 282 where they are iterated over. I took a crude peek to see where the disappearing act was happening with var_dump($this->cookies); die; but couldn't find out where the problem started.

I changed addCookie to:
public function addCookie( Cookie $cookie ) {
$this->cookies[] = $cookie;
return setcookie($cookie->name, $cookie->value, $cookie->expires, $cookie->path, $cookie->domain, $cookie->secure, $cookie->httponly);
}
because by sendHeaders(), there's nothing to iterate through.

Route User-Agent Condition

Allow routes to match an expected User-Agent string like this:

Slim::get('/foo/bar', function () {
    //Render template for SongBird
})->agent('Songbird (\d\.\d)[\d\/]*?');

plugins

within the hooks - how would you pass on the Slim object to classes created within hooks and exchange data with the object? tried to pass on Slim::$app but its private.

thanks!

(sorry, for bothering you all day long - trying to get used to the framework and im writing some plugins right now)

Timezone Not Set Triggers Application Error

When using Slim::lastModified(time()) I'm running into an Application Error. I'm using Slim (latest Git rev) on nginx 0.7.67, php5.3.3 via FastCGI on OS X 10.6:

The application could not run because of the following error:
Details:
Message: date() [function.date]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Berlin' for 'CEST/2.0/DST' instead
File: /Users/hexa/Code/api-v2.slim/slim/Slim.php
Line: 561

nginx Configuration

I've been having some trouble getting Slim to play nice with nginx; the site at the root is implementing Slim, but the sub-folders have other apps (Wordpress for example).

This is what I have so far; any thoughts?

    location / {
        index bootstrap.php;
        try_files $uri $uri/ /bootstrap.php; 
       # the working WP configuration takes ?q=$1 parameters; should Slim as well?
       # try_files ~ if ( !-e $request_uri ), only less taxing.
    }

Warning in Request file

When I test slim framework in my environment (PHP 5.3.3, display_errors at true and error_reporting at E_ALL), I've this warning in index file :

Warning: preg_replace() [function.preg-replace]: No ending delimiter '@' found in path\slim\Request.php on line 194

Content Negotiation

I am opening this issue for discussion only for now. This is a very large feature, and I would like to settle on an approach before moving to code. Post your thoughts here! I will post my own thoughts on the subject later tonight when I have more time.

Application-wide Route Conditions

Implement Route::$conditions which are automatically applied to all application routes. This will be an associative array... [ $key => $regex ].

Improve Slim cookie management

Cookie management is terrible thus far. Need to import the Request's cookies into the Request object and make them accessible. Also refactor how cookies are managed in the Response so that cookies are sent with the Request rather than when set.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.