Coder Social home page Coder Social logo

panique / mini2 Goto Github PK

View Code? Open in Web Editor NEW
416.0 65.0 102.0 878 KB

Just an extremely simple naked PHP application, useful for small projects and quick prototypes.

License: MIT License

PHP 51.19% Shell 9.90% JavaScript 1.39% Twig 30.54% SCSS 6.98%

mini2's Introduction

MINI2 - A naked barebone PHP application

MINI 2

What is MINI 2 ?

An extremely simple PHP barebone / skeleton application built on top of the wonderful Slim router / micro framework [1] [2] [docs].

MINI is by intention as simple as possible, while still being able to create powerful applications. I've built MINI in my free-time, unpaid, voluntarily, just for my personal commercial and private use and uploaded it on GitHub as it might be useful for others too. Nothing more. Don't hate, don't complain, don't vandalize, don't bash (this needs to be said these days as people treat tiny free open-source private scripts like they paid masses of money for them). If you don't like it, don't use it. If you see issues, please create a ticket. In case you want to contribute, please create a feature-branch, never commit into master. Thanks :)

Mini currently uses Slim 2.6.0.

There's also MINI 1, an earlier version of MINI2, but with totally different code! Since August 2016 there's also MINI 3, an improved version of MINI 1. While MINI2 uses Slim under the hood, MINI 1 and 3 are 100% native PHP.

Features

  • built on Slim
  • RESTful routes
  • extremely simple: the entire application is just 2 .php files (plus external dependencies plus view templates)
  • uses Twig as template engine, others are possible (via Slim packages)
  • uses pure PDO instead of ORM (it's easier to handle)
  • basic CRUD functions: create, read, update/edit and delete content
  • basic search
  • basic AJAX demo
  • (optional) shows emulated PDO SQL statement for easy debugging
  • (optional) compiles SCSS to CSS on the fly
  • (optional) minifies CSS on the fly
  • (optional) minifies JS on the fly
  • (optional) dev/test/production switch

By default MINI allows user access to /public folder. The rest of the application (including .git files, swap files, etc) is not accessible.

Requirements

  • PHP 5.3+
  • MySQL
  • mod_rewrite activated, document root routed to /public (tutorial below)

Maybe useful: Simple tutorials on setting up a LAMP stack on Ubuntu 14.04 LTS and 12.04 LTS.

License

MIT, so feel free to use the project for everything you like.

Screenshot

MINI2 - A naked PHP skeleton application on top of Slim

Support the project

Support the project by renting a server at DigitalOcean or just tipping a coffee at BuyMeACoffee.com. Thanks! :)

Buy Me A Coffee

Installation (in Vagrant, 100% automatic)

If you are using Vagrant for your development, then you can install MINI with one click (or one command on the command line). MINI comes with a demo Vagrant-file (defines your Vagrant box) and a demo bootstrap.sh which automatically installs Apache, PHP, MySQL, PHPMyAdmin, git and Composer, sets a chosen password in MySQL and PHPMyadmin and even inside the application code, downloads the Composer-dependencies, activates mod_rewrite and edits the Apache settings, downloads the code from GitHub and runs the demo SQL statements (for demo data). This is 100% automatic, you'll end up after +/- 5 minutes with a fully running installation of MINI2 inside an Ubuntu 14.04 LTS Vagrant box.

To do so, put Vagrantfile and bootstrap.sh from Mini/_vagrant inside a folder (and nothing else). Do vagrant box add ubuntu/trusty64 to add Ubuntu 14.04 LTS ("Trusty Thar") 64bit to Vagrant (unless you already have it), then do vagrant up to run the box. When installation is finished you can directly use the fully installed demo app on 192.168.33.77. As this just a quick demo environment the MySQL root password and the PHPMyAdmin root password are set to 12345678, the project is installed in /var/www/html/myproject.

Auto-Installation on Ubuntu 14.04 LTS (in 10 seconds)

You can install MINI2 including Apache, MySQL, PHP and PHPMyAdmin, mod_rewrite, Composer, all necessary settings and even the passwords inside the configs file by simply downloading one file and executing it, the entire installation will run 100% automatically. See the bootstrap.sh file for more infos (and the default passwords). Keep in mind that this is quick dev setup, not a perfect choice for production for sure. This should work perfectly in every naked Ubuntu 14.04 LTS.

Download the installer script

wget https://raw.githubusercontent.com/panique/mini2/master/Mini/_vagrant/bootstrap.sh

Make it executable [is this necessary ?]

chmod +x bootstrap.sh

Run it! Boooooom. Give it some minutes to perform all the tasks. And yes, you can thank me later :)

sudo ./bootstrap.sh

Installation (manual)

1. Activate mod_rewrite and ...

Tutorials for Ubuntu 14.04 LTS and Ubuntu 12.04 LTS.

2. ... route all requests to /public folder of the script

Change the VirtualHost file from DocumentRoot /var/www/html to DocumentRoot /var/www/html/public and from <Directory "/var/www/html"> to <Directory "/var/www/html/public">. Don't forget to restart. By the way this is also mentioned in the official Slim documentation, but hidden quite much.

3. Edit the development database configs

Inside public/index.php edit the database credentials and fill in your values.

4. Execute the SQL statements

In _install folder (for example with PHPMyAdmin) to create the demo database.

5. Get dependencies via Composer

Do a composer install in the project's root folder to fetch the dependencies (and to create the autoloader).

Basic usage

See index.php in /public. The code below will basically show /view/subpage.twig when user moves to yourproject.com/subpage !

$app->get('/subpage', function () use ($app) {
    $app->render('subpage.twig');
});

Same like above here, but this time the $model is passed to the route (use ($app, $model)), so it's possible to perform model actions (database requests, data manipulation, etc). Action getAllSongs() is called, the result $songs (obviously an array of songs) passed to the view (view/songs.twig) via 'songs' => $songs.

$app->get('/songs', function () use ($app, $model) {

    $songs = $model->getAllSongs();

    $app->render('songs.twig', array(
        'songs' => $songs
    ));
});

Inside the view the data is easily rendered like this (the template engine Twig is used here). Twig makes the view extremely simple and secure. Instead of doing this <?php echo htmlspecialchars($song->id, ENT_QUOTES, 'UTF-8'); ?> inside your HTML-Twig-template you can simply do {{ song.id }} which automatically escapes and echos $song["id"], $song->id etc. Fantastic! See the full Twig documentation here.

{% for song in songs %}
<tr>
    <td>{{ song.id }}</td>
    <td>{{ song.artist }}</td>
</tr>
{% endfor %}         

The content of the model (currently in Mini\model\model.php) is extremely simple, it's just some methods getting data. When the model is initialized the database connection is created automatically (just one time for sure). A typical model method:

public function getAllSongs()
{
    $sql = "SELECT id, artist, track, link FROM song";
    $query = $this->db->prepare($sql);
    $query->execute();

    return $query->fetchAll();
}

Configuration

Index.php holds the configs for a development environment. Self-explaining.

$app->configureMode('development', function () use ($app) {
    $app->config(array(
        'debug' => true,
        'database' => array(
            'db_host' => 'localhost',
            'db_port' => '',
            'db_name' => 'mini',
            'db_user' => 'root',
            'db_pass' => '12345678'
        )
    ));
});

Environment switch (development / test / production)

To implement a production config simply copy the whole config block above and replace development with production. Add an environment variable to your Apache config. More here and here.

Before/after hooks

Slim can perform things at certain points in the lifetime of an application instance, for example before everything is started. MINI uses this to perform SASS-to-CSS compiling and CSS / JS minification via external tools (loaded via Composer btw). This is inside the above development environment configuration to make sure these actions are not made in production for sure.

$app->hook('slim.before', function () use ($app) {

    // SASS-to-CSS compiler @see https://github.com/panique/laravel-sass
    SassCompiler::run("scss/", "css/");

    // CSS minifier @see https://github.com/matthiasmullie/minify
    $minifier = new MatthiasMullie\Minify\CSS('css/style.css');
    $minifier->minify('css/style.css');

    // JS minifier @see https://github.com/matthiasmullie/minify
    $minifier = new MatthiasMullie\Minify\JS('js/application.js');
    $minifier->minify('js/application.js');
});

Why $_POST['x'] instead of Slim's post/get handler ?

Because it's simpler and more native. Feel free to use the Slim handlers if this fits more your workflow.

Why is the deletion of a song not made with a DELETE request ?

Because (against popular opinion) HTML4/5 does not support other HTTP methods than GET/POST (but the browsers themselves do). The most easy workaround is doing this with GET/POST. Please write a ticket if I'm totally wrong here.

Glitches

  1. /songs/ is not the same as /songs !
  2. Writing the initialization in the short syntax like $app = new \Slim\Slim(array('view' => ...)); has some issues and might eventually break your application. Using the syntax like in index.php works fine. @see http://help.slimframework.com/discussions/questions/954-twig-getenvironment-function-no-longer-available-using-slim-views

Useful: Organize view templates in sub-folders

It's possible to organize the view templates for sure, simply do $app->render('folder1/folder2/index.twig');.

Useful: Multiple router files

When all the routes in index.php are too much for you: Create a folder routers, put your route(r)s into files like xxx.router.php and load them like this:

$routers = glob('../routers/*.router.php');
foreach ($routers as $router) {
    require $router;
}

Useful: get URL inside view (1)

Twig can get the URL, use this in the app

$twig->parserExtensions = array(
    new \Slim\Views\TwigExtension(),
);

and then use {{ baseUrl() }} in the view template.

Useful: get URL inside view (2)

Or manually add the baseUrl:

$app->hook('slim.before', function () use ($app) {
    $app->view()->appendData(array('baseUrl' => '/base/url/here'));
});

and use it in the view template via {{ baseUrl }}. More here.

Scripts used

SASS Compiler https://github.com/panique/php-sass

CSS / JS Minifier http://www.mullie.eu/dont-build-your-own-minifier/

Interesting

http://de.slideshare.net/jeremykendall/keeping-it-small-getting-to-know-the-slim-php-microframework

Injecting stuff into $app: http://www.slimframework.com/news/version-230

Slim apps https://github.com/ccoenraets/wine-cellar-php https://github.com/xsanisty/SlimStarter

https://github.com/indieisaconcept/slim-bower-server/blob/master/app/config.php

Route URL Rewriting / Installation http://docs.slimframework.com/#Route-URL-Rewriting

Change log

  • [panique] upgrade from Slim 2.5 to 2.6
  • [panique] upgrade from Slim 2.4.3 to 2.5.0
  • [sim2github] renamed model path to uppercase to fit PSR-4

Support the project

Support the project

mini2's People

Contributors

bitdeli-chef avatar panique avatar sim2github 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

mini2's Issues

[new feature] basic JSON API example

Just a supersimple example! Would be cool if people with experiences in API-writing could give some guidance here, you know, doing it the right way.

navigation does not work

I resolved problem with homepage, it is showing now after commenting out skip-networking in my.cnf file, however navigation does not redirect, when I click on link home/exampleone I get error 404 url not found, I have mod_rewrite installed and working.

[TODO] What about using .env

We are using this framework for a small development but we have modified the index.php to use an .env with https://github.com/vlucas/phpdotenv
Since we use git for our deployments we think it's safer not to store passwords from different environments in the same file, so .env it's actually ignored on git and there's one in every environment.
I have forked the repo and I can commit this change to pull request but I wanted to know if someone is actually interested in this change.

Global functions

Hi,

I would like to know how i can make global functions and how to use them.

So let me give an example.

I have an sort of Core file, where i can get stuff out of my database and these outputs can i use everywhere in the .twig files like an {{ constant('whatever') }}.

I don't know how i can do this.

[improvement] grouping routes

Routes that have parts in common can be grouped. Damn, I love Slim!

$app->group('/songs', function () use ($app, $container) {

    $app->get('/', function () use ($app, $container) { ... }
    $app->get('/xxx', function () use ($app, $container) { ... }
    $app->get('/yyy', function () use ($app, $container) { ... }

}

[new feature] super-basic unit test integration

Can somebody who's experienced with unit testing give infos about

  1. how to test the database connection
  2. how to properly pass the database connection to tested models/model methods
  3. how to restructure the project to make everything testable as possible

MINI2 license

Hi!

Although it seems fairly obvious that MINI2 is completely open-source, I'm wondering if it'd be possible to explicitly give the project a license in the README or via a license file (e.g. MIT, GPL, Apache, etc)? Doing so would be immensely useful when it comes to using MINI2 in projects that require all licenses to be explicitly stated.

Cheers!

[discussion] How could the architecture of this be improved ?

MINI2 currently consists of 2 simple .php files:

  1. /public/index.php, holding the initialization of Slim and Twig, the configs, the loading of the model and the routes for sure.
  2. MINI/model/model.php, which holds the data handling methods, so it's more or less the model.

MINI2 is just a quick thing I've built for quick projects (in daily agency work you have setup sometimes 3 applications per week), and using real frameworks is totally overdoze in most cases, so this makes sense.

However, it might be better to
a.) move the configs
b.) split the model to multiple files, so the user can organize data-handling methods (like classic UserModel extends Model, you know what I mean :) ).
c.) move the routes, split the routes to multiple files

What do you think ? Ideas ? Code ? Feature branches ?

uncaught PDOException

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Connection refused' in /srv/http/php-mvc-advanced/application/libs/controller.php on line 35

I get this error, what might be the reason? Thanks.

[check] Possible issue in loadModel()

So im a total nub when it comes to php and mvc so i might be totaly wrong here. Basicly i was trying to create a private function in my controler to do some basic checks and use it within other methods. While invoking this private method i came across error "Fatal error: Cannot redeclare class ....". After some googling i managed to fix this by changing "require" to "require_once" in loadModel method in libs/application.php (line 48). If this isnt an issie then sorry to bother You. if it is then You could check libs/controller.php for any possible similar errors.

[moved to MINI3] Rebuild the model from one file to 1+ files

Currently the model is just one class in one file. Totally okay for the main purpose of this script. But this is for sure not cool when your model gets bigger. Possible idea:

  1. Use autoloading and static methods for model calls, so you could use something like UserModel::getUserById(17) everywhere in your app.
  2. Or, autoload different model-classes, so the current $model->getAllSongs(); would get another level, like $model->SongModel->getAllSongs();

Where do i put sass-compiler.php ?

NEVER MIND NEVER MIND NEVER MIND NEVER MIND. I THOUGHT COMPOSER WULDN'T WORK ON MAC. I WAS WRONG. ITS ACTUALLY THE EASIEST THING I'VE EVER INSTALLED FROM TERMINAL.

I have changed the composer.json, created a folder called vendor, and put sass-compiler.php in there. I am still getting Fatal error: Class 'SassCompiler' not found in /Applications/AMPPS/www/php-mvc-advanced-master/index.php on line 27. I got sass-compiler.php from https://github.com/panique/laravel-sass . Please help. I will temporarily comment out line 27 in index.php for now. Thanks, and great project. I can't wait to learn how to use and play around with TWIG and SASS compiler.

[new feature] basic search example

while showing different possibilities of how to do searches, plus explaining the costs of these:
LIKE, MATCH AGAINST, external libs (Solr), etc.

[new feature] add feedback messages

Giving out application-wide feedback (positive, negative, etc.) after successful/failed actions could be a useful feature. I moved this ticket here from php-mvc basic version.

[new feature] perfect PSR-4 integration (composer, unit tests, etc)

It would be cool to have a perfect PSR-4 autoloader implementation here. Feel free to commit/push such thing into develop branch. The integration should be as correct as possible and also touch the composer autoloading (psr-4 is recommended here according to some good Stackoverflow answers) and possible unit testing.

Q : More URL parameters

First off big thank you for this/the basic version which has helped me no end. I was looking at extending the URL parameters by using an array and modifying the split URL and then just calling it in the construct if it exsists/not empty

My question is it safe to directly call the params $this->home->method($param_1, $param_2,3,4,5) from the one array or is there a reason the url_controller, url_action and params are kept seperate?

This is how I'm validating the url before parsing it to the 'filteredparam' array:

function spliturl ($string){

    $untrusted = ltrim($string);
    $ut2 = rtrim($untrusted,'/');
    $ut3 =  htmlspecialchars($ut2);     
    $ut4 = explode('/', $ut3);

    $filteredparam;
    $this->paramindex = 0;

    foreach ($ut4 as $testcase) {
    if (preg_match('/^[\w-]+$/',$testcase)) {        
        $this->filteredparam[$this->paramindex] = quickvalidate($testcase);    
    }
    $paramindex++;
    }
    return $filteredparam;   
}

function quickvalidate($string){
        $clear = strip_tags($string);
        $clear = html_entity_decode($clear);
        $clear = urldecode($clear);
        $clear = preg_replace('/[^A-Za-z0-9]/', ' ', $clear);
        $clear = preg_replace('/ +/', '', $clear);
        $clear = trim($clear);
        return $clear;  
}

cannot setup vhost to /public

My webhosting company doesn't allow me to set vhost.

I just can upload the files to "public_html"

I try to setup the following .htaccess at public_html folder.
It shows page not found.

But I can access the page via http://www.abc.com/public/.

My web hosting server works fine for Mini1 for the following .htaccess
RewriteEngine on
RewriteRule ^(.*) public/$1 [L]

It does not work for Mini2

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.