Giter Site home page Giter Site logo

lime's Introduction

Lime

Lime is a micro web framework for quickly creating web applications in PHP with minimal effort.

$app = new Lime\App();

$app->bind("/", function() {
    return "Hello World!";
});

$app->run();

Just include one file (~ 35KB) and you're ready to go.

Routes

In Lime, a route is an HTTP method paired with a URL-matching pattern. Each route is associated with a block:

$app->get("/", function() {
    return "This was a GET request...";
});

$app->post("/", function() {
    return "This was a POST request...";
});

$app->bind("/", function() {
    return "This was a GET or POST request...";
});

Routes are matched in the order they are defined. The first route that matches the request is invoked.

Route patterns may include named parameters, accessible via the params hash:

$app->get("/posts/:id/:name", function($params) {
    return $params["id"].'-'.$params["name"];
});

$app->post("/misc/*", function($params) {
    return $params[":splat"];
});

$app->bind("#/pages/(about|contact)#", function($params) {
    return implode("\n", $params[":captures"]);
});

Conditions

Routes may include a variety of matching conditions, such as the user agent:

$app->get("/foo", function() {
    // GET request...
}, strpos($_SERVER['HTTP_USER_AGENT'], "Safari")!==false);

Create Urls

$route = $app->routeUrl('/my/route');
$url   = $app->baseUrl('/assets/script.js');

Templates

In general you can utilize any template engine you want. Lime provides a simple template engine:

$app->get("/", function() {

        $data = array(
            "name"  => 'Frank',
            "title" => 'Template demo'
        );

        return $this->render("views/view.php with views/layout.php", $data);
});

views/view.php:

<p>
    Hello <?=$name?>.
</p>

views/layout.php:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
        <meta charset="UTF-8">
        <title><?=$title?></title>
</head>
<body>
        <a href="<?=$this->routeUrl('/')?>">Home</a>
        <hr>
        <?php echo $content_for_layout;?>
</body>
</html>

You like OO style?

Just bind a class:

class Pages {

    protected $app;

    public function __construct($app){
        $this->app = $app;
    }

    /*
        accessible via
        /pages or /pages/index
    */
    public function index() {
        return $this->app->render("pages/index.php");
    }

    /*
        accessible via
        /pages/contact
    */
    public function contact() {
        return $this->app->render("pages/contact.php");
    }

    /*
        accessible via
        /pages/welcome/foo
    */
    public function welcome($name) {
        return $this->app->render("pages/welcome.php", array("name"=>$name));
    }
}

// bind Class to map routes
$app->bindClass("Pages");

Registry

Store any values by setting a key to the $app object.

$app["config.mykey"] = array('test' => 123);

Path access helper with /

$value = $app["config.mykey/test"]; // will return 123

Paths

Register paths for quicker access

$app->path('views', __DIR__.'/views');

$view = $app->path('views:detail.php');
$view = $app->render('views:detail.php');

Gets url to file

$url  = $app->pathToUrl('folder/file.php');
$url  = $app->pathToUrl('view:file.php');

Dependency injection

$app->service("db", function(){

    // object will be lazy created after accessing $app['db']
    $obj = new PDO(...);

    return $obj;

});

$app["db"]->query(...);

Events

// register callback
$app->on("customevent", function(){
    // code to execute on event
}, $priority = 0);

// trigger custom events
$app->trigger("customevent", $params=array());

You can utilize three system events: before, after and shutdown

// render custom error pages

$app->on("after", function() {

    switch($this->response->status){
        case "404":
            $this->response->body = $this->render("views/404.php");
            break;
        case "500":
            $this->response->body = $this->render("views/500.php");
            break;
    }
});

Helpers

You can extend Lime by using your custom helpers:

class MyHelperClass extends Lime\Helper {

    public function test(){
        echo "Hello!";
    }
}

$app->helpers["myhelper"] = 'MyHelperClass';

$app("myhelper")->test();

Build in helpers

Session

$app("session")->init($sessionname=null);
$app("session")->write($key, $value);
$app("session")->read($key, $default=null);
$app("session")->delete($key);
$app("session")->destroy();

Cache

$app("cache")->setCachePath($path);
$app("cache")->write($key, $value, $duration = -1);
$app("cache")->read($key, $default=null);
$app("cache")->delete($key);
$app("cache")->clear();

lime's People

Contributors

aheinze avatar croupier avatar faulancer avatar peterbrinck avatar raffaelj 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

lime's Issues

password_hash

This version of Lime requires PHP >=5.5 because of using function password_hash.

Syntax error in readme 'Events' example

In the events section, as far as I can tell,

$app->response["status"] and $app->response["body"]

should be:

$app->response->status and $app->response->body

Lime/App.php in Cockpit is far away from this repo

I think about using Lime for an application and I just compared the both files App.php from Cockpit and from this repo. I realized many differences between both applications. As far as I understood, Lime is a dependency of Cockpit and should also work as a standalone micro framework. The version bundled with Cockpit has some improvements and a lot of cleanup.

@artur Do you plan to update this repo and to keep it in sync with the cockpit version?

Oh - and the license info at the top of App.php is the content of MIT License, but the headline "MIT License" is missing.

Q: Why DiC with helpers?

I choice Lime for my next project with MongoLite (thanks for this 2 great projects), but i check the code and i think is useless use helpers and DiC in the same app, you want split the helpers for internal objects and DiC for external objects?

More dynamic App::set()

I really like your framework, but I stumbled upon the rather redundant code of App::set(). I'd suggest to use something like this instead:

public function set($key, $value) {
    $keys = explode('/',$key);

    if (count($keys)>5) return false;

    $registry =& $this->registry;

    foreach ($keys as $key) {
        $registry =& $registry[$key];
    }

    $registry = $value;

    return $this;
}

That way you also won't have to limit the number of keys (but I kept the limit in case you had good reasons for it ^^).

output qrcode

use qrcode library, some code:

    $params['data'] = 'This is a text to encode become QR Code';
    $this->response->mime = 'png';
    $this->qrcode->generate($params);

But generate return None and output binary, response status is 404 will echo Path not found.
Please give me some advice.

App->render() seems not to work during "after" event

I'm working more or less directly from the the Events example in the readme. When I try to render 404.php I get two errors:

[01-Jul-2014 20:52:26 UTC] PHP Warning: include(views/404.php): failed to open stream: No such file or directory in /Users/scott/Sites/Semantic_Redesign/cockpit/vendor/Lime/App.php on line 529

and

[01-Jul-2014 20:52:26 UTC] PHP Warning: include(): Failed opening 'views/404.php' for inclusion (include_path='.:/Applications/MAMP/bin/php/php5.4.4/lib/php') in /Users/scott/Sites/Semantic_Redesign/cockpit/vendor/Lime/App.php on line 529

I'm able to render templates normally (i.e. when there's a defined route using bind()) but not during the after event.

http status

How do i change the http status for my post routes exactly? It's always 404 and api testers can't return the output.

$app->pathToUrl not work

$app->pathToUrl("site:upload/common/logo.svg");
always return false;

problem in $app->path() method
in this line:
if (!isset($this->paths[$parts[0]])) return false;
in this line $this->paths property is empty, but in other iterations, it normally contains paths.

bindClass method not work

on App.php line 855:

$pattern = '#^'.str_replace('\*', '(.*?)', preg_quote($route, '#')).'#';

explame:
$pattern = '#^/action/(.*?)#';
$path = '/action/edit';

result:
$matches is empty

^/action/(.*)# is ok

Using helper shortcut from routed classes

I have a class routed automatically: $app->bindClass('Admin');

From functions in that class I can access helpers using the long version, but not the shorthand:

  • Works: $this->app->helper('db')
  • Does not work: $this->app('db')

The second call fails: Call to undefined method Admin::app()

Language URLs

I'm having trouble formulating a bind pattern that works for detecting language slugs, while still correctly collecting page slugs from the URL (so the actual page loads).

The 3 patterns I'm trying to use are as follows:

"#/(en|de)?\/?$#"
"#/(en|de)?#/:slug"
"#/(en|de)?\/?gallery#"

The actual function for the :slug URL is as follows:

$app->bind("#/(en|de)?\/?#:slug", function($params) use($app) {
    $post = collection('Pages')->findOne(["Slug_slug"=>$params['slug']]);
    return $app->render('views/page.php', ['post' => $post]);
});

The first one works as expected: it matches /, /en, /en/, /de and /de/. And the gallery pattern matches /gallery, /en/gallery and /de/gallery. The problem is that all URLs that rely on :slug return a "path not found" error.

I've tried the pattern with the closing delimiter after :slug, but have not had any success. Is there an obvious issue I'm missing?

Post Json body data

i trying with post json body data but not work, i cannot get body data

example request data

{
"hello":"world"
}

Assigning routes for pagination

From the documentation I cannot see a way of capturing url's for pagination. Currently I have 2 routes woth the exact same code. Anyone who has a solution to handle this?

/page/:name/entries/
/page/:name/entries/p/1/

Module

Wie organisiert man ein Projekt mit Modulen?
Gibt es einen Blog/ Dokumention zum Lime Framework?

Root OO Class

I'm trying to bind a class as the root route. Something like: "http://mysite.com/" showing the "index" method of my class "Pages". And not "http://mysite.com/pages".

I've tried using the second param of bindClass method (alias) with an empty string, like:
$app->bindClass("Pages", "");

But it fails using the "alias" param when an empty string returns false for a soft test at line 778:
$clean = $alias ? $alias : trim(strtolower(str_replace("\\", "/", $class)), "\\");

So, I could fix this changing the bindClass method. The changed lines are 778 and 780:

778 - $clean = $alias !== false ? $alias : trim(strtolower(str_replace("\\", "/", $class)), "\\");
779 - 
780 - $this->bind(empty($clean) ? '/*' : '/'.$clean.'/*', function() use($self, $class, $clean) {

Maybe you could update it too ;)

Notice: Undefined index: base_url

last commit code:
Notice: Undefined index: base_url in /srv/http/lime/core/Lime/App.php on line 202
Notice: Undefined index: base_route in /srv/http/lime/core/Lime/App.php on line 203

Warning: file_exists(): open_basedir restriction in effect

In #7 PHP Warning issue not only on $app->on("after", function(){, because ob_end_clean

Warning: file_exists(): open_basedir restriction in effect. File(views:test.php) is not within the allowed path(s): (/srv/http/:/home/:/tmp/:/usr/share/pear/:/usr/share/webapps/:/proc/) in /srv/http/limewiki/app/core/Lime/App.php on line 419

AND var_dump($this->isAbsolutePath('views:test.php')); return true;

about style and script

I use $app->style('/assets/css/style.css') will echo:

<link href="/assets/css/style.css" type="text/css" rel="stylesheet">

but my webapp is subdirectory /srv/http/test/, href should be /test/assets/css/style.css, I know use $app->style($app->baseUrl('/assets/css/style.css')).

Q: Set content-type when using render method?

I'm in the process of testing out Cockpit CMS, which encourages the use of Lime in all their examples. So far, the only issue I've had is while trying to create a JSON file in PHP (from data in the Cockpit API) that I want to use for a small react app. The page is assigned the content-type text/html, instead of application/json, even though the view contains a header('Content-Type: application/json; charset=UTF-8').

Is there a way to change the content-type when using the $app-render() method, or is there a recommended solution to this?

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.