i'm want to creating a design pattern and use the "Blade templating engine".
Can I use the Blade templating engine outside of Laravel and use it in my new pattern ?
For the record:
I tested many libraries to run blade outside Laravel (that i don't use) and most are poor hacks of the original library that simply copied and pasted the code and removed some dependencies yet it retains a lot of dependencies of Laravel.
So I created (for a project) an alternative for blade that its free (MIT license, i.e. close source/private code is OK) in a single file and without a single dependency of an external library. You could download the class and start using it, or you could install via composer.
https://github.com/EFTEC/BladeOne
https://packagist.org/packages/eftec/bladeone
It's 100% compatible without the Laravel's own features (extensions).
How it works:
<?php
include "lib/BladeOne/BladeOne.php";
use eftec\bladeone;
$views = __DIR__ . '/views'; // folder where is located the templates
$compiledFolder = __DIR__ . '/compiled';
$blade=new bladeone\BladeOne($views,$compiledFolder);
echo $blade->run("Test.hello", ["name" => "hola mundo"]);
?>
Another alternative is to use twig but I tested it and I don't like it. I like the syntax of Laravel that its close to ASP.NET MVC Razor.
Edit: To this date (July 2018), it's practically the only template system that supports the new features of Blade 5.6 without Laravel. ;-)
You certainly can, there are lots of standalone blade options on packagist, as long as you are comfortable with composer then there should be no issue, this one looks pretty interesting due to having a really high percentage of stars compared to downloads.
Be warned though i have not tried it myself, like you i was looking for a standalone option for my own project and came across it, i will be giving it a real good workout though at sometime in the near future,
Matt Stauffer has created a whole repository showing you how you can use various Illuminate components directly outside of Laravel. I would recommend following his example and looking at his source code.
https://github.com/mattstauffer/Torch
Here is the index.php of using Laravel Views outside of Laravel
https://github.com/mattstauffer/Torch/blob/master/components/view/index.php
You can write a custom wrapper around it so that you can call it like Laravel
use Illuminate\Container\Container;
use Illuminate\Events\Dispatcher;
use Illuminate\Filesystem\Filesystem;
use Illuminate\View\Compilers\BladeCompiler;
use Illuminate\View\Engines\CompilerEngine;
use Illuminate\View\Engines\EngineResolver;
use Illuminate\View\Engines\PhpEngine;
use Illuminate\View\Factory;
use Illuminate\View\FileViewFinder;
function view($viewName, $templateData)
{
// Configuration
// Note that you can set several directories where your templates are located
$pathsToTemplates = [__DIR__ . '/templates'];
$pathToCompiledTemplates = __DIR__ . '/compiled';
// Dependencies
$filesystem = new Filesystem;
$eventDispatcher = new Dispatcher(new Container);
// Create View Factory capable of rendering PHP and Blade templates
$viewResolver = new EngineResolver;
$bladeCompiler = new BladeCompiler($filesystem, $pathToCompiledTemplates);
$viewResolver->register('blade', function () use ($bladeCompiler) {
return new CompilerEngine($bladeCompiler);
});
$viewResolver->register('php', function () {
return new PhpEngine;
});
$viewFinder = new FileViewFinder($filesystem, $pathsToTemplates);
$viewFactory = new Factory($viewResolver, $viewFinder, $eventDispatcher);
// Render template
return $viewFactory->make($viewName, $templateData)->render();
}
You can then call this using the following
view('view.name', ['title' => 'Title', 'text' => 'This is text']);
Yes you can use it where ever you like. Just install one of the the many packages available on composer for it.
If you're interested in integrating it with codeigniter I have a blog post here outlining the process.
Following the above steps should make it obvious how to include it into any framework.
Related
I'm not very experienced with php projects structure, I found this awesome and simple tutorial: https://arjunphp.com/creating-restful-api-slim-framework/ how to create simple slim rest app.
This is actually PHP SLIM's official project structure, my question is what is best and proper way to add and use RedBean php ORM, I dont want on every route to include something like this
use \RedBeanPHP\R as R;
R::setup( 'mysql:host=localhost;dbname=mydatabase', 'myusername', 'mypassword)
and then
$book = R::load( 'book', $id );
And then use ReadBean for my db stuff. Im wondering how to include RedBeans into project and then just use it where i need it. This is my project structure https://github.com/iarjunphp/creating-restful-api-slim-framework3.
Note: i added red beans via composer like its described here https://github.com/gabordemooij/redbean
You can put the code for setting up your libraries in any file that is going to be included on each request, so assuming you're using slim/slim-skeleton, src/dependencies.php is probably the place you want to add these two lines:
use \RedBeanPHP\R as R;
R::setup( 'mysql:host=localhost;dbname=njux_db', 'root', '');
Then you can use ReadBeans in your route callbacks but you also need to add the use \RedBeanPHP\R as R; statement to your src/routes.php as well (or any file that is going to use this class)
If you use a MVC framework (which I recommend) like codeigniter it's pretty easy.
You only have to copy your rb.php to the application/third_party folder.
Then create a file called application/libraries/rb.php containing a code like this one.
<?php
class Rb {
function __construct() {
include(APPPATH.'/config/database.php');
include(APPPATH.'/third_party/rb.php');
$host = $db[$active_group]['hostname'];
$user = $db[$active_group]['username'];
$pass = $db[$active_group]['password'];
$db = $db[$active_group]['database'];
R::setup("mysql:host=$host;dbname=$db", $user, $pass);
}
}
?>
...and vôila. RedBean will read your database configuration from CodeIgniter's standard file application/config/database.php and you will be able to use any R:: command from anywhere in your code. No includes, not additional code required :-)
The template engine called blade can be used with codeigniter or pure php? I know that it can be used with laravel and I'd like to know if also can be used with any other php framework or with pure php
Blade can be used stand-alone in PHP.
This means you can comfortably use it in CodeIgniter.
https://github.com/PhiloNL/Laravel-Blade
Then again, you will need composer for that.
Alternatively you could use this CodeIgniter Library to simulate Blade: CodeIgniter Slice-Libray
It works pretty like Blade and it was designed directly for CodeIgniter!
For the record and as answer to another post:
I tested many libraries to run blade outside Laravel (that i don't use) and most (with all respect of the coders) are poor hacks of the original library that simply copied and pasted the code and removed some dependencies yet it retains a lot of dependencies of Laravel.
I created an alternative for blade that its free (MIT license, i.e. close source/private code is OK) in a single file and without a single dependency of an external library. You could download the class and start using it, or you could install via composes (composer require eftec/bladeone). So even composer is optional.
https://github.com/EFTEC/BladeOne
https://packagist.org/packages/eftec/bladeone
Its 100% compatible sans the Laravel's own features (extensions).
You can use BladeView library for CI.
NB: I ported this library
class Welcome extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library("bladeview");
}
public function renderView(){
$data=array(
"name"=>"Jhon",
"age"=>21
);
$this->bladeview->render("test", $data);
}
public function renderString(){
$data=array(
"name"=>"Jhon",
"age"=>21
);
$string="Hello I'm \{{$name}}. My age is \{{$age}}";
$this->bladeview->render($string, $data,false);
}
}
then in view.blade.php you can render like you do in laravel blade.
Hello my name is {{$name}}. My Age is {{$age}}.
Output:
Hello my name is Jhon. My Age is 21.
I have done a full write up here: http://mstd.eu/index.php/2017/03/02/using-the-laravel-blade-templating-engine-in-codeigniter-3/
Basically, include the package with composer (you need to set CI up to use composer), then create a blade instance passing it your view and cache folder like so:
$blade = new BladeInstance(__DIR__ . "/../views", __DIR__ . "/../cache/views");
echo $blade->render("index");
Lately I've been using a template manager for silex, but I've noticed that it's been abandoned and no longer works for newer versions of silex. Here's an example code of what it does (it can be seen on its GitHub page):
<?php
use Herrera\Template\TemplateServiceProvider;
use Silex\Application;
$app = new Application();
$app->register(new TemplateServiceProvider(), array(
'template.dir' => '/path/to/dir',
'template.dir' => array(
'/path/to/dir1',
'/path/to/dir2',
'/path/to/dir3',
)
));
$app['template.engine']->render('test.php');
So, what it exactly does is that it renders the file you give, and you can also give other parameters to send it to the file before rendering it... It was very useful to me, but as I said, it's been abandoned and it no longer works with newer versions of Silex.
So, what I'm asking is: is it a good alternative of this that works with newer versions? Should I downgrade my Silex in order to be able to use this? Or is it very hard to try to "create" a system for being able to use this?
I've heard about Twig, but it doesn't really convince me because it doesn't seem to be convenient with what I want to achieve.
Thanks!
You can have the same result just extending the twig loader (Twig_Loader_Filesystem).
$app['twig.loader.filesystem'] = $app->share(
$app->extend('twig.loader.filesystem', function($loader, $app) {
$loader->addPath('/path/to/dir1');
$loader->addPath('/path/to/dir2');
$loader->addPath('/path/to/dir3');
return $loader;
}
);
Then you just use twig as always. $app['twig']->render('template.twig', array(...));
The filesystem loader will look for templates in /path/to/dir1, and if they dont exists it will fallback to look for them in /path/to/dir2 and so on.
If you insist in using a pure PHP templating engine you can do it with the Symfony Templating Component:
Install with composer symfony/templating and then register the service:
use Symfony\Component\Templating\PhpEngine;
use Symfony\Component\Templating\TemplateNameParser;
use Symfony\Component\Templating\Loader\FilesystemLoader;
$app['templating'] = $app->share(function() {
$loader = new FilesystemLoader(array(
'/path/to/dir1',
'/path/to/dir2',
'/path/to/dir3',
));
$nameParser = new TemplateNameParser();
$templating = new PhpEngine($nameParser, $loader);
return $templating;
});
Then you just use this engine as $app['templating']->render('template.php', array(...));
I am trying to use highchart in cakephp and have followed the below tutorial and also the stackoverflow post on the subject.
I still get a highchart not found.
I downloaded highchartPHP and placed all the 4 files in Vendor/HighchartsPHP
In the layout, I add the lines with the actual js files in webroot/js
echo $this->Html->script('jquery-1.9.1.min'); // Include jQuery library
echo $this->Html->script('highcharts'); // Include jQuery library
This is my code
<?php
App::import('Vendor', 'HighchartsPHP/Highchart');
class ChartsController extends AppController
{
public function index() {
$chart = new Highchart(); /////////////////Error: Class 'Highchart' not found
$chart->chart = array(
'renderTo' => 'container', // div ID where to render chart
'type' => 'line'
);
$chart->series[0]->name = 'Tokyo';
$chart->series[0]->data = array(7.0, 6.9, 9.5);
$this->set( compact( 'chart' ) );
}
In view file
<?php $chart->printScripts(); ?>
<script type="text/javascript">
<?php echo $chart->render("chart");?>
</script>
https://coderwall.com/p/c6yasq
Using HighchartsPHP library in CakePHP
I can't find any more instructions about cakePHP setup with highcharts so I am stuck and I get a highchart not found error.
I still have something missing. What has confused me is that highchartPHP doesn't explain how you install it for a MVC version with cakephp.
How to setup highchart so it works in cakephp ?
I got from the download zip button link so it must be v3
https://github.com/ghunti/HighchartsPHP
also Error: Class 'Highchart' not found from the controller as I outlined above
That's what happens when people don't mention version numbers...
...a year later nobody knows what they were talking about anymore. The tutorial and the question are most probably about version 1.x.
https://github.com/ghunti/HighchartsPHP/tree/v1.0
So a quick fix would be to use v1, but I'm not sure if that's a very good idea as it's probably not maintained anymore.
Namespaces and Composer
Look at the source code of version 2.x and 3.x, they are now using namespaces, and so the class cannot be found when not pointing into that namespace properly.
As mentioned on the projects homepage the library should be installed via composer, and with pretty much all those libraries using composer the generated autoloader needs to be used, but this isn't really the place here to explain how to use composer, this is already extensively covered all over the net.
https://getcomposer.org/doc/00-intro.md
Be sure to check out the CakePHP docs on how to use the composer autoloader with CakePHP too:
[...]
If you’re installing any other libraries with Composer, you’ll need to setup the autoloader, and work around an issue in Composer’s autoloader. In your Config/bootstrap.php file add the following:
// Load Composer autoload.
require APP . 'Vendor/autoload.php';
// Remove and re-prepend CakePHP's autoloader as Composer thinks it is the
// most important.
// See: http://goo.gl/kKVJO7
spl_autoload_unregister(array('App', 'load'));
spl_autoload_register(array('App', 'load'), true, true);
http://book.cakephp.org/.../advanced-installation.html#installing-cakephp-with-composer
Is there any standard library to do Rails style URL mapping in PHP? I am not using any framework, all the code is hand-written. Basically, I am looking for a library that does this
example.com/user/1/active
this should map to a user, with id = 1 and status = 2 (those being the parameters). I should be able to define the map.
There are roughly ten thousand ways to do this in PHP.
I've recently become a fan of klein.php, a lightweight bit of router code with some handy convenience methods. It's not a framework, and doesn't get in the way of you using one if you wanted to.
It's basically little more than "here's a URL pattern, and here's the function to run when the pattern matches."
Frameworks are really built to handle that automatically, but short of using a framework, you would be best off writing your own .htaccess rules (if you are using linux or os x), or try checking out how say, CakePHP handles url rewriting and base off of that.
Example:
http://example.com/name/corey
RewriteRule ^(.+)/(.+)$ /$1.php?name=$2 [NC,L]
That would rewrite the above url to /name.php?name=corey
PHP's purpose is not to handle differently formatted URLs. There should be some custom application logic taking care of this.
You've mentioned that you are not using any framework at this moment, so I would like to propose you to include Silex, it's a micro framework based on the components of Symfony 2.
Here's the 'Hello World' example:
require_once __DIR__.'/silex.phar';
$app = new Silex\Application();
$app->get('/hello/{name}', function($name) use($app) {
return 'Hello '.$app->escape($name);
});
$app->run();
You've mentioned that you are currently using PHP 5.2. Silex uses namespaces, which are available from PHP 5.3 and so on, so you will have to upgrade your PHP to take this approach.
Go with Symfony framework.
http://symfony.com/blog/new-in-symfony-1-2-toward-a-restful-architecture-part-1
Look at this response:
https://stackoverflow.com/questions/238125/best-framework-for-php-and-creation-of-restful-based-web-services