Error using Slim framework and Twig template - php

I'm trying to make Slim work with Twig template system, this is part of my index.php
// Twig [Template]
require 'Extras/Views/Twig.php';
TwigView::$twigDirectory = __DIR__ . '/vendor/Twig/lib/Twig/';
//Slim
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim(array(
'view' => $twigView
));
And this is my structure
Extras
|_Views
|_Twig.php
Slim
templates
vendor
|_Twig
|_lib
|_Twig
index.php
I try several times with other configurations and searching buy I ALLWAYS get this error:
Fatal error: Class 'Slim\View' not found in C:\wamp\www\slim\Extras\Views\Twig.php on line 43
Can anyone help me here? All the examples I had found was using composer

Ok, I solve it.
This is the solution:
// Slim PHP
require "Slim/Slim.php";
\Slim\Slim::registerAutoloader();
// Twig
require "Twig/lib/Twig/Autoloader.php";
Twig_Autoloader::register();
// Start Slim.
/** #var $app Slim */
$app = new \Slim\Slim(array(
"view" => new \Slim\Extras\Views\Twig()
));
And this is my structure now.
Slim
|_Extras
|_Views
|_Twig.php
|_Slim
templates
Twig
|_lib
|_Twig
|_Autoloader.php
index.php
¡I hope this help someone else!

Now Slim-Extras is DEPRECATED, we must use Slim-Views (https://github.com/codeguy/Slim-Views):
require "Slim/Slim.php";
\Slim\Slim::registerAutoloader();
$slim = new \Slim\Slim( array(
'debug' => false,
'templates.path' => 'fooDirTemplates',
'view' => '\Slim\Views\Twig'
));
$twigView = $slim->view();
$twigView->parserOptions = array(
'debug' => false
);
$twigView->parserDirectory = 'Twig';
$twigView->parserExtensions = array(
'\Slim\Views\TwigExtension'
);
$slim->notFound( 'fooNotFoundFunction' );
$slim->error( 'fooErrorFunction' );
// SLIM routes...
$slim->run();

If someone is still running in to this issue.
The problem for me was that I had installed both slim/views AND slim/twig-view.
I uninstalled slim/views and it worked

Related

How to import/use package installed with Composer?

I'm just getting started with PHP and I ran into a small problem.
I've downloaded a package using composer require <package_name> and now I'm not sure how to access it from my .php file. I tried bunch of things but I couldn't make it work.
I'm trying to use this package: https://packagist.org/packages/giggsey/libphonenumber-for-php
EDIT:
This is the code I use to test:
<?php
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
// Instantiate app
$app = AppFactory::create();
// Add Error Handling Middleware
$app->addErrorMiddleware(true, false, false);
// Register routes
$routes = require __DIR__ . '/../app/routes.php';
$routes($app);
$swissNumberStr = "044 668 18 00";
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
try {
$swissNumberProto = $phoneUtil->parse($swissNumberStr, "CH");
var_dump($swissNumberProto);
} catch (\libphonenumber\NumberParseException $e) {
var_dump($e);
}
// Run application
$app->run();
And it says: Undefined type 'libphonenumber\PhoneNumberUtil'.

Why can't i import ciphersweet StringProvider

I installed ciphersweet on my server using composer but when i try to import the library i'm getting this error.
Fatal error: Uncaught Error: Class 'ParagonIE\CipherSweet\KeyProvider\StringProvider' not found in index.php.
Seems like the dependency didn't install correcty, i'm lost can you help please.
It's a php error.
here's my code :
use ParagonIE\CipherSweet\EncryptedRow;
use ParagonIE\CipherSweet\Transformation\AlphaCharactersOnly;
use ParagonIE\CipherSweet\Transformation\FirstCharacter;
use ParagonIE\CipherSweet\Transformation\Lowercase;
use ParagonIE\CipherSweet\Backend\FIPSCrypto;
use ParagonIE\CipherSweet\KeyProvider\StringProvider;
$provider = new StringProvider('a981d3894b5884f6965baea64a09bb5b4b59c10e857008fc814923cf2f2de558');
$engine = new CipherSweet($provider, new FIPSCrypto());
/** #var CipherSweet $engine */
$row = (new EncryptedRow($engine, 'contacts'))
->addTextField('first_name')
->addTextField('last_name')
->addFloatField('latitude')
->addFloatField('longitude');
// Notice the ->addRowTransform() method:
$row->addCompoundIndex(
$row->createCompoundIndex(
'contact_first_init_last_name',
['first_name', 'last_name'],
64, // 64 bits = 8 bytes
true
)
->addTransform('first_name', new AlphaCharactersOnly())
->addTransform('first_name', new Lowercase())
->addTransform('first_name', new FirstCharacter())
->addTransform('last_name', new AlphaCharactersOnly())
->addTransform('last_name', new Lowercase())
);
$prepared = $row->prepareRowForStorage([
'first_name' => 'Jane',
'last_name' => 'Doe',
'latitude' => 52.52,
'longitude' => -33.106,
'extraneous' => true
]);
var_dump($prepared);
?>
You need to load the vendor/autoload.php in order for the installed packages to work.
For example, add require_once __DIR__ . '/vendor/autoload.php'; to the top of your file.
This will make php aware of the namespaces in your packages.
You might need to change this if your files are not in the root directory of your application. For example, if your files are in app/ directory, those files need to use require_once __DIR__ . '/../vendor/autoload.php'
See https://getcomposer.org/doc/01-basic-usage.md#autoloading for more details.

php Fatal error: Uncaught Error: Class 'Router' not found in

<?php
$query = require 'core/bootstrap.php';
$router = new Router();
require 'routes.php';
$uri = trim($_SERVER['REQUEST_URI'],'/');
require $router->direct($uri);
I don't get what I missed, tried to require Router.php file but nothing help searched for google for that error bug was getting only cake.php answers
$router ->define([
' ' =>'controllers/index.php',
'about' => 'controllers/about.php',
'about/culture' => 'controllers/about-culture.php',
'contact' => 'controllers/contact.php'
]);
that's routes.php file
Hey You are requiring routes.php after new Router(); line. I assume your Router class is present in routes.php file
Hence try below code
$query = require 'core/bootstrap.php';
require 'routes.php';
$router = new Router();
$uri = trim($_SERVER['REQUEST_URI'],'/');
require $router->direct($uri);

Symfony 2 ESI Cache

I have an action which is called in all my page (for logged people only), this action retrieves recent tweets from my twitter account.
API access is limited so I would like the result of this action to be in cache for 10 minutes
public function socialAction(){
$consumerKey = $this->container->getParameter('consumer_key');
$consumerSecret = $this->container->getParameter('consumer_secret');
$accessToken = $this->container->getParameter('access_token');
$accessTokenSecret = $this->container->getParameter('access_token_secret');
// on appel l'API
$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
$screen_name = "blabla";
$tweets = $tweet->get('statuses/user_timeline', [
'screen_name' => $screen_name,
'exclude_replies' => true,
'count' => 50
]);
$tweets = array_splice($tweets, 0, 5);
$response = $this->render('GestionJeuBundle:Default:social.html.twig', array("tweets" => $tweets));
$response->setPublic();
$response->setSharedMaxAge(600);
return $response;
}
To enable caching I have made ​​the following changes
app/config/config.yml
framework:
esi: { enabled: true }
fragments: { path: /_proxy }
and
app/AppCache.php
<?php
require_once __DIR__.'/AppKernel.php';
use Symfony\Bundle\FrameworkBundle\HttpCache\HttpCache;
class AppCache extends HttpCache
{
protected function getOptions()
{
return array(
'debug' => false,
'default_ttl' => 0,
'private_headers' => array('Authorization', 'Cookie'),
'allow_reload' => false,
'allow_revalidate' => false,
'stale_while_revalidate' => 2,
'stale_if_error' => 60,
);
}
}
and
web/app_dev.php
<?php
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| !in_array(#$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '.....', 'fe80::1', '::1'))
) {
header('HTTP/1.0 403 Forbidden');
exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();
require_once __DIR__.'/../app/AppKernel.php';
require_once __DIR__.'/../app/AppCache.php';
$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$kernel = new AppCache($kernel);
// When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter
Request::enableHttpMethodParameterOverride();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);
error_log($kernel->getLog());
Despite that the page is updated every page refresh (after testing, it does exactly the same things in production environment with change on app.php too)
Have I misunderstood or forgotten a thing ?
Thank you in advance for your help.
EDIT solve : i was rendering this action with
{{render(controller("GestionJeuBundle:Default:social")) }}
changing it for
{{render_esi(controller("GestionJeuBundle:Default:social")) }}
solve my problem
Hexune
i was rendering this action with
{{render(controller("GestionJeuBundle:Default:social")) }}
changing it for
{{render_esi(controller("GestionJeuBundle:Default:social")) }}
solve my problem
As far as I experimented last weeks, it's worth noting that if you use debug environment in Symfony, Varnish always passes-by your request to the back-end.

TYPO3 6.2 ext_autoload with non-namespaced classes

I'm trying to create a new Extension on Extbase in TYPO3 6.2 and im failing at including an existing Class/Framework Module.
My ext_autoload.php (ofc located in my extension dir)
$extensionPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('couponprinter');
return array(
'ZendPdf' => $extensionPath . '/Classes/Utility/Zend/Pdf.php',
);
I'm trying to load the class in my controller via
$pdf = $this->objectManager->create('ZendPdf');
But im gettin the error "Could not analyse class:ZendPdf maybe not loaded or no autoloader?"
The Zend class itself has tons of includes which I cant refactor all, so I need the autoloader. Here is a short snippet:
/** Internally used classes */
require_once 'Zend/Pdf/Element.php';
require_once 'Zend/Pdf/Element/Array.php';
require_once 'Zend/Pdf/Element/String/Binary.php';
require_once 'Zend/Pdf/Element/Boolean.php';
require_once 'Zend/Pdf/Element/Dictionary.php';
require_once 'Zend/Pdf/Element/Name.php';
require_once 'Zend/Pdf/Element/Null.php';
require_once 'Zend/Pdf/Element/Numeric.php';
require_once 'Zend/Pdf/Element/String.php';
class Zend_Pdf{
// code of the class
}
Since TYPO3 6.2 changed some old methods, I can't include anymore. Does anyone have a idea how I can load a not-namespaced class into a extbase extension?
You need to create a ext_autoload.php file and fill it with something like
<?php
$extensionClassesPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('news') . 'Classes/';
$default = array(
'tx_news_domain_model_dto_emconfiguration' => $extensionClassesPath . 'Domain/Model/Dto/EmConfiguration.php',
'tx_news_hooks_suggestreceiver' => $extensionClassesPath . 'Hooks/SuggestReceiver.php',
'tx_news_hooks_suggestreceivercall' => $extensionClassesPath . 'Hooks/SuggestReceiverCall.php',
'tx_news_utility_compatibility' => $extensionClassesPath . 'Utility/Compatibility.php',
'tx_news_utility_importjob' => $extensionClassesPath . 'Utility/ImportJob.php',
'tx_news_utility_emconfiguration' => $extensionClassesPath . 'Utility/EmConfiguration.php',
'tx_news_service_cacheservice' => $extensionClassesPath . 'Service/CacheService.php',
);
return $default;
?>
Found in the documentation at http://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/Autoloading/Index.html
I guess it should be
$extensionPath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('couponprinter');
return array(
'zendpdf' => $extensionPath . '/Classes/Utility/Zend/Pdf.php',
);
The left side of the array (keys) must be lowercase.

Categories