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(...));
Related
I'm trying to rewrite a "custom framework" application to the Symfony, but I can not do everything at once, so I've divided the process into steps.
From important notes - I've already implemented the symfony/templating component and the symfony/twig-bridge component.
That's how I want to output the form in the template:
<?php echo $view['form']->form($form) ?>
As I'm doing so the following error is thrown:
Symfony\Component\Form\Exception\LogicException
No block "form" found while rendering the form.
/var/www/html/vendor/symfony/form/FormRenderer.php on line 98
To render the templates I'm using the DelegatingEngine which uses the PhpEngine and the TwigEngine.
Setting up the Twig with the \Symfony\Bridge\Twig\Extension\FormExtension is well documented, but what I'm missing is the php setup. This is how I'm doing this:
new \Symfony\Component\Form\Extension\Templating\TemplatingExtension($phpEngine, $this->csrfManager());
Could you point me what am I missing or what's wrong with my setup?
I think the simplest way would have been to install the Symfony 3.3 standard edition next to your app (pending the release of Symfony Flex).
After this, find a way to use the router of Symfony with the router of your application.
So you could have the full Symfony framework, create your form type in it and let Symfony render it :
With an ajax call
With a new Symfony Kernel in your legacy app
I've found the answer:
I was using the wrong FormRendererEngineInterface. Instead of relying on the \Symfony\Component\Form\Extension\Templating\TemplatingExtension class I've registered the form helper by myself:
$phpEngine = new PhpEngine(new TemplateNameParser(), new FilesystemLoader(realpath(__DIR__.'/../Template').'/%name%'));
$twigEngine = new TwigEngine($this->twig(), new TemplateNameParser());
$this->TemplateEngine = new DelegatingEngine(array(
$phpEngine,
$twigEngine,
));
$phpEngine->addHelpers(array(
new FormHelper(new FormRenderer($this->twigFormRendererEngine())),
));
As you can see in the TemplatingEngine:
public function __construct(PhpEngine $engine, CsrfTokenManagerInterface $csrfTokenManager = null, array $defaultThemes = array())
{
$engine->addHelpers(array(
new FormHelper(new FormRenderer(new TemplatingRendererEngine($engine, $defaultThemes), $csrfTokenManager)),
));
}
It relies on the TemplatingRendererEngine while I need the TwigRendererEngine instance, as the form templates are the twig files.
Correct me if my explanation is wrong, but the solution is working.
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.
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
I'm trying to use FirePHP with Zend Framework 2, but there seems to be something missing. Here's the basic code I'm trying to run:
$writer = new Zend\Log\Writer\FirePhp();
$logger = new Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('FirePHP logging enabled');
The error I get is "FirePHP Class not found". I was initially puzzled because I do have a FirePhp class in my Zend/Log/Writer folder. But then I saw that the class constructor requires a FirePhp\FirePhpInterface object. So I checked the Zend/Log/Writer/FirePhp folder and there's a FirePhpBridge class in there that implements FirePhpInterface, but it also requires a FirePHP instance in the constructor. I don't have any FirePHP.php file in my Zend/Log/Writer/FirePhp folder. Am I supposed to get this from somewhere else?
Update
I now have managed to get FirePHP working, but I'm trying to figure out how to do it in a clean way so this works. The only way I've gotten it to work is putting it in the root directory of my project and doing the following:
include_once('FirePHP.php');
$writer = new Zend\Log\Writer\FirePhp(new Zend\Log\Writer\FirePhp\FirePhpBridge(FirePHP::getInstance(true)));
$logger = new Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('FirePHP logging enabled');
I assume that normally I should be able to create a writer like so:
$writer = new Zend\Log\Writer\FirePhp();
However, where this goes wrong I believe is in the getFirePhp() function of the Zend\Log\Writer\FirePhp class. The class does this:
if (!$this->firephp instanceof FirePhp\FirePhpInterface
&& !class_exists('FirePHP')
) {
// No FirePHP instance, and no way to create one
throw new Exception\RuntimeException('FirePHP Class not found');
}
// Remember: class names in strings are absolute; thus the class_exists
// here references the canonical name for the FirePHP class
if (!$this->firephp instanceof FirePhp\FirePhpInterface
&& class_exists('FirePHP')
) {
// FirePHPService is an alias for FirePHP; otherwise the class
// names would clash in this file on this line.
$this->setFirePhp(new FirePhp\FirePhpBridge(new FirePHPService()));
}
This is where I get lost as to how I'm supposed to set things up so that this class_exists('FirePHP') call finds the right class and new FirePHPService() also works properly.
First you should add this code to Module.php of your module
return array(
//...
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
);
and here content of autoload_classmap.php
<?php
return array(
'FirePHP' => realpath(APPLICATION_PATH . '/vendor/FirePHP').'/FirePHP.php',
);
FirePHP.php(renamed from FirePHP.class.php) downloaded from official site.
then you can write below code in any place of your module and it will work
use Zend\Log\Writer\FirePhp;
use Zend\Log\Logger;
$writer = new FirePhp();
$logger = new Logger();
$logger->addWriter($writer);
$logger->info("hi");
Am I supposed to get this from somewhere else?
Yes, you need to get FirePHP into your project and autoloading.
If you're using composer (and I recommend that you do), just add:
"firephp/firephp-core" : "dev-master"
(or similar) in your composer.json and update. If you're not using composer, you should grab the firephp libs, and let your autoloader know about them.
I'd love to see some code here rather than enjoy some sourse outside. =)
A solution could be to use the Zend_Service_Amazon_S3 component that's provided in Zend Framework -- if it's like many other components of ZF, it might be possible to use it outside of the framework, without having to do too much work to "extract" it.
I've never used it, but there are some examples of code on that manual page, and it doesn't seem too hard to use (quoting) :
require_once 'Zend/Service/Amazon/S3.php';
$s3 = new Zend_Service_Amazon_S3($my_aws_key, $my_aws_secret_key);
$s3->createBucket("my-own-bucket");
$s3->putObject("my-own-bucket/myobject", "somedata");
echo $s3->getObject("my-own-bucket/myobject");
(There are a couple of other examples I won't copy-paste)
An advantage of using a Zend Framework component is that ZF has (mostly) a good reputation, with code that's tested, maintained, supported, ...
Another solution could be to use this Amazon S3 PHP class ; I've never used it either, though...
<?php
require_once("sdk.class.php");
$s3 = new AmazonS3();
$bkt = (strtolower)$s3->key . "-bucket00";
$res = $s3->create_bucket($bkt, AmazonS3::REGION_US_E1);
?>