• Stars
    star
    280
  • Rank 147,492 (Top 3 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A PHP router that helps you create webapps and APIs effortlessly

Link

A minimal router for your php webapps and APIs that effortlessly links all your project. Its fast and to the point.

Features

  • RESTful routing
  • Wildcards for your limitless creativity
  • Named routes to help you create links easily
  • Self documented, speaks its own legacy
  • Before and after routes function support
  • Tested with PHP >5.3

HHVM Version

HHVM version of Link can be found at https://github.com/bmbsqd/Link-Hack . Thanks to Andy Hawkins for creating it.

Installation

Composer

For install from composer just add the following line to your project's composer.json file

	"require" : {
    	"link/link" : "dev-master"
    }

Then run php composer.phar install

Manually

Run git clone https://github.com/apsdehal/Link.git in your project's home directory and include it using

	require("Link/src/Link.php");

Basics

Simple Routing

Routing is too simple with Link, following example supports it:

<?php

function routeMe(){
	echo 'I am routed';
}

Link::all( array(
	'/' => 'routeMe'
));

Named Routing

In Link routes can be named and then further used generatings links in a simple and elegant way.

<?php

function nameMe(){
	echo 'I am named';
}

Link::all( array(
	'/named' => ['nameMe', 'Its my name']
));

Names to routes must be given as second argument in array while the first being the route handler.

Usage

These named routes can be used in creating in hassle free links.

	<a href="<?php echo Link::route('Its my name') ?>">Go to named route</a>

Routing with classes

Link can handle classes as Route handler easily, but remember non-static class will be handled RESTfully.

<?php

$routes = array(
	'/' => 'IndexController::getMeHome', //Static function
    '/home' => 'HomeController', //RESTful class
    '/office' => 'OfficeController'
);

Link::all($routes)

RESTful routing

RESTful routing is a breeze for Link.

<?php

class HomeController
{
	
    function get(){
    	echo 'You have got to home :)';
    }
    
    function post(){
    	echo 'You have posted to home';
    }
    
    function put(){
    	echo 'You have put to home';
    }
    
    function delete(){
    	echo 'You have deleted the home :(';
    }
}

Link::all( array (
	'/' => ['HomeController', 'HomeRoute']
));

WildCards

Link supports numbers, string and alphanumeric wildcards which can be used as {i} {s} {a} respectively and of course it can render regex also. Example will clear away your doubts

$routes = array(
	'/' => 'IndexController',
    '/{i}' => 'IndexController',
    //Parameter in place of {i} will be passed to IndexController
	'/posts/{a}/{i}/{s}' => 'PostsController'
);

Link::all($routes);

Supplimentary Handlers

Universal Extra Handlers

Through Link, universal before and after handlers can be added, such that these are executed always before any route is routed. This can be done as follows:

<?php
function universalBeforeHandler( $id ) {
    echo 'Hello I occured before with ' . $id . '\n';
}

function universalAfterHandler( $id ) {
    if( $id )
        echo 'Hello I occured after with ' . $id;
    else
        echo 'I simply occured after';
}

function main(){
    echo 'I simply occured\n'
}

Link::before( 'universalBeforeHandler', ['12'] ); //If you want to pass parameters to them, pass them as arrays
Link::before( 'universalBeforeHandler'); //else don't even pass them

Link::all( array(
    '/' => 'main'
    ))

Now go to '/' in your browser to find:

Hello I occured before with 12

I simply occured

I simply occured after.

Single Route

You can add a before (middle) handler to a specific route, just pass the before handler to routes array as third parameters. The wildcards extracted from route will be passed to to before handler and if it return some array, this array will be passed further to main handler but if not the original extracted wildcards would be passed away. Make sure you return an array from before handler.

<?php 
function beforeHandler( $name ) {
    return [ $name . ' Link' ];
}

function mainHandler( $name ){
    echo $name;
}

Link::all(array(
    '/{s}' => ['mainHandler', 'Main', 'beforHandler']
    ));

Go to '/aps' in browser, you will get aps Link.

Passing Parameters to Named Routes

You can pass parameters to named routes if the have wildcards in the route path, this will thus generate dynamic links through a single named route.

<?php

function nameMe( $i, $s ){
	echo 'I am named and I have been passed ' . $i . $s ;
}

Link::all( array(
	'/named/{i}/{s}' => ['nameMe', 'Its my name']
));

Now generate a link through Link

echo Link::route( 'Its my name', array(1, 'Me') );

This in turn will generate YOUR_DOMAIN/named/1/Me.

404 Errors

You should probably add a 404 handler to your routes array, rest Link will take care of handling routes that are not found. In case, Link doesn't find a 404 route defined, it will just send a 404 header.

Server Configuration

Apache

You should add the following code snippet in your Apache HTTP server VHost configuration or .htaccess file.

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond $1 !^(index\.php)
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Alternatively, in a version of Apache greater than 2.2.15, then you can use this:

FallbackResource /index.php

Notes

If you are planning to use non-Restful method and non-static classes, then use them as follows:

class HelloHandler 
{
    public function home(){
        echo 'Hello home';
    }
}

$helloObject = new HelloHandler();

Link::all( array(
    '/' => array( $helloObejct, 'home' )
    ))

So you need to pass such functions as array( $object, 'functionName' )

Contributions

Thanks to all people below for contributing to Link.

  • @jedmiry
  • @pborelli

License

Link is available under MIT license, so feel free to contribute and modify it as you like. Free software, Yeah!

More Repositories

1

awesome-ctf

A curated list of CTF frameworks, libraries, resources and softwares
JavaScript
9,761
star
2

go-logger

Simple logger for Go programs. Allows custom formats for messages.
Go
286
star
3

gym-starcraft

StarCraft: BroodWars OpenAI Gym environment
Python
81
star
4

Konsoole

HTTP Monitoring Console written in Go
Go
65
star
5

Face-Recognition

Face Recognition project in PyTorch using CNNs
Python
39
star
6

HackPy

A collection of notes and script that will help you learn basics of hacking with Python
Python
34
star
7

Flappy-Bird-Servo-Automation

Flappy Bird Automation using RL and Servo
JavaScript
28
star
8

qunit-migrate

Migrate old QUnit tests to 2.x. Uses regex and ASTs to convert old QUnit code.
JavaScript
17
star
9

structured-query-engine

Elasticsearch like search engine supporting real time indexing and querying
Python
14
star
10

hm_example_mmf

The Hateful Memes Challenge example code using MMF
Python
13
star
11

flava-tutorials

Tutorials for FLAVA model https://arxiv.org/abs/2112.04482
Jupyter Notebook
12
star
12

ic3net-envs

Environments with IC3Net paper
Python
12
star
13

torrent-to-magnet

Takes a torrent file and returns it's magnet uri
JavaScript
9
star
14

Limelight

A light toned, justifying theme for Jekyll
CSS
8
star
15

movie-recommendations

Movie Recommendations Application based on Structured Query Engine
Python
7
star
16

Heuristics-Problem-Solving

Algorithms for Heuristics course at NYU Fall 2016
Python
6
star
17

Zap

Minimalistic python based Wikipedia article's PPT generator
Python
6
star
18

spaces-to-tabs

Convert spaces to tabs in your files
JavaScript
5
star
19

Crunch

A mobile app that lets you get most out of Muzi
JavaScript
4
star
20

nli-batch-optimizations

Better convergence speeds for NLI task
Python
4
star
21

Shortest-Adversarial-Path-Architecture

Architecture for Shortest Adversarial Path
JavaScript
3
star
22

SPOJ

SPOJ solutions
C++
3
star
23

Cluster

Repo for Mesosphere Challenge
JavaScript
3
star
24

WikidataAnnotationFeeder

A plugin based on Pundit that help you create annotations and feed them on Wikidata.
JavaScript
3
star
25

mp3-length

NPM module for calculating length of a mp3 file
JavaScript
2
star
26

apsdehal.github.io

Personal Blog
CSS
2
star
27

blackjack

A simple JS and HTMl Blackjack game.
JavaScript
2
star
28

string-constants

String definitions for easy use
JavaScript
2
star
29

Programming-Languages-Assignments

Programming Languages Assignments
TeX
2
star
30

alexa-skill-math-hero

An alexa skill for playing multiple choice mathematics questions trivia
JavaScript
2
star
31

lein-clj-service

Lein template for a clojure service.
Clojure
2
star
32

PyScripts

Python
1
star
33

Opti.js

Registry for tracking instantiated models
JavaScript
1
star
34

Laravel-test-app

Test app made to learn Laravel
PHP
1
star
35

att.js

Helps in easy binding of events to dynamic html.
JavaScript
1
star
36

Project

1
star
37

ds-queue

Simple Queue Data Structure.
JavaScript
1
star