Twig template (unable to create cache directory) - php

Installed twig templating system into my application and works fine however when i attempt to specify a cache directory within the configuration it doesn't allow me to continue "Unable to create the cache directory (../view/c/91)".
However when I set the cache to just "cache", for some reason it writes the cache folder into the root of my drive rather than the root of the web folder where it is hosted?
$loader = new Twig_Loader_Filesystem('../view');
$twigConfig = [
'debug' => true,
'cache' => '../view/cache'
];
App::register('view', 'Twig_Environment', array($loader, $twigConfig), function($twig) {
$twig->addExtension(new Twig_Extension_Debug());
});

Try this:
$loader = new Twig_Loader_Filesystem(__DIR__ . '/view');
$twigConfig = [
'debug' => true,
'cache' => __DIR__ . '/view/cache'
];
App::register('view', 'Twig_Environment', array($loader, $twigConfig), function($twig) {
$twig->addExtension(new Twig_Extension_Debug());
});

'cache' => __DIR__ . '/view/cache' instead use
'cache' => $_SERVER['DOCUMENT_ROOT'] .'your_folder_structure/view/cache'

Related

Slim v4 Creating Log File

So, my issue is that I'm having trouble to make Slim record all its actions inside a file (for example : app.log). I ran across a lot of tutorials and other forum similar to this one but the issue was that they were using the v3 of the Slim Framework.
I saw some post suggesting things like this inside a settings.php :
return [
'settings' => [
'displayErrorDetails' => true, // set to false in production
'addContentLengthHeader' => false, // Allow the web server to send the content-length header
// Renderer settings
'renderer' => [
'template_path' => __DIR__ . '/../templates/',
],
// Monolog settings
'logger' => [
'name' => 'my-app',
'path' => __DIR__ . '/../logs/' . $logDate->format('Y-m-d') . 'app.log',
],
],
];
But the issue with that method is that, well, settings aren't set up this way anymore in v4. So here I am. Stuck. If anybody could give me a hand, it'll help a lot !
To load the settings within a container you have to add a container definition for it.
Example settings file: config/settings.php
return [
// set to false in production
'displayErrorDetails' => true,
// Renderer settings
'renderer' => [
'template_path' => __DIR__ . '/../templates/',
],
// Monolog settings
'logger' => [
'name' => 'my-app',
'path' => __DIR__ . '/../logs/' . date('Y-m-d') . '_app.log',
],
];
Example container entry in config/container.php:
use Psr\Container\ContainerInterface;
// ...
return [
// ...
'settings' => function () {
return require __DIR__ . '/settings.php';
},
// Add more entries here ...
}
To fetch the settings within the container use this:
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
// ...
return [
// ...
LoggerInterface::class => function (ContainerInterface $container) {
$settings = $container->get('settings');
$name = $settings['logger']['name'];
$logger = new Logger($name);
// Add logger handler...
return $logger;
},
// ...
}
Tip: For autowiring support it's better to use an collection object instead of an simple "string" as container identifier. Read more

Slim 3 - Error is not shown

I am trying to use zeuxisoo/slim-whoops to show errors, but for some reason I am only getting white screen without any message show. This is the code I am using (I don't know if it does matter, I am using quick PHP host (php -S localhost:8000):
require __DIR__ . '/../vendor/autoload.php';
$app = new Slim\App([
'settings' => [
'displayErrorDetails' => true,
'debug' => true,
'whoops.editor' => 'sublime',
]
]);
$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware);
Make sure that your file begins with <?php and that after your $app->add(...); you call $app->run();:
<?php
require __DIR__ . '/../vendor/autoload.php';
$app = new Slim\App([
'settings' => [
'displayErrorDetails' => true,
'debug' => true,
'whoops.editor' => 'sublime',
]
]);
$app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware);
$app->run();

Class Users not found in Phalcon 2

So basically I just installed Phalcon 2.0 on my ubuntu machine, with apache2, mysql and all the stuff installed. I went straight into the documentation of Phalcon to get me started. After following the exact steps from their tutorial, I got this error:
Fatal error: Class 'Users' not found in /var/www/html/phalcon/tutorial/app/controllers/SignupController.php on line 14
I think it may be related to namespacing of classes and stuff like that, but I wasn't able to figure it out so far.
Looks like you didn't register your folders properly. I add a resume of my code to give you an idea.
File index.php
use Phalcon\Mvc\Micro;
use Phalcon\Events\Manager as EventsManager;
define('APP_DIR', dirname(__DIR__) .'/');
try {
$config = require APP_DIR .'config/config.php';
require APP_DIR .'config/loader.php';
...
} catch (Exception $e) {}
File config.php
return new Phalcon\Config([
'application' => [
'environment' => 'development',
'controllers' => APP_DIR .'controllers/',
'library' => APP_DIR .'library/',
'models' => APP_DIR .'models/',
'plugins' => APP_DIR .'plugins/',
'routes' => APP_DIR .'routes/',
'logs' => APP_DIR .'logs/',
'base_uri' => '/',
'debug' => false
]
]);
File loader.php
<?php
$loader = new \Phalcon\Loader;
// Register directories
$loader->registerDirs([
$config->application->controllers,
$config->application->library,
$config->application->models,
$config->application->plugins,
])->register();
// Composer autoloader
require_once APP_DIR .'vendor/autoload.php';
This should resolve any class specified in config folders.

Why i do not gain performance using ClassMapAutoloader in Zend Framework 2?

In my company we developing a ZF2 application, no programm;-), right now. We are at a point where we want to test some part of the application by bringing it into the public www.
We prepared a STAGE-environment and i do some performance tuning now. I read that using the ClassMapAutoloader is much faster than the StandardAutoLoader like described e.g. http://samminds.com/2012/11/zf2-performance-quicktipp-2-classmap-autoloading/ . I do understand why it should be faster but in my case i profiled the site with and without ClassMapAutoloader using xdebug profiling, WinCacheGring/QCacheGrind and it is slower about 0,2%.
Does anyone has an idea why this could be slower?
I am using CentOS and PHP Version => 5.6.12
EDIT ADDED INFORMATION:
Example of one autoload_classmap.php:
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
'Search\Elasticsearch\Document\AbstractDocument' => __DIR__ . '/src/Search/Elasticsearch/Document/AbstractDocument.php',
'Search\Elasticsearch\Document\ArticleDocument' => __DIR__ . '/src/Search/Elasticsearch/Document/ArticleDocument.php',
'Search\Elasticsearch\Document\BookingDocument' => __DIR__ . '/src/Search/Elasticsearch/Document/BookingDocument.php',
'Search\Elasticsearch\Document\DocumentType' => __DIR__ . '/src/Search/Elasticsearch/Document/DocumentType.php',
'Search\Elasticsearch\Document\InvoiceDocument' => __DIR__ . '/src/Search/Elasticsearch/Document/InvoiceDocument.php',
'Search\Elasticsearch\Document\OfficeDocument' => __DIR__ . '/src/Search/Elasticsearch/Document/OfficeDocument.php',
'Search\Elasticsearch\Document\OfficeMemberDocument' => __DIR__ . '/src/Search/Elasticsearch/Document/OfficeMemberDocument.php',
'Search\Elasticsearch\Document\ProductDocument' => __DIR__ . '/src/Search/Elasticsearch/Document/ProductDocument.php',
'Search\Elasticsearch\Document\ProfileDocument' => __DIR__ . '/src/Search/Elasticsearch/Document/ProfileDocument.php',
'Search\Elasticsearch\Document\RatingDocument' => __DIR__ . '/src/Search/Elasticsearch/Document/RatingDocument.php',
'Search\Elasticsearch\Document\AbstractWebSearchDocument' => __DIR__ . '/src/Search/Elasticsearch/Document/AbstractWebSearchDocument.php',
'Search\Elasticsearch\AutoSuggestionQueryHandler' => __DIR__ . '/src/Search/Elasticsearch/AutoSuggestionQueryHandler.php',
'Search\Elasticsearch\SearchStatisticIndexHandler' => __DIR__ . '/src/Search/Elasticsearch/SearchStatisticIndexHandler.php',
'Search\Elasticsearch\TermRecognizerQueryHandler' => __DIR__ . '/src/Search/Elasticsearch/TermRecognizerQueryHandler.php',
'Search\Elasticsearch\SearchIndexHandler' => __DIR__ . '/src/Search/Elasticsearch/SearchIndexHandler.php',
'Search\Elasticsearch\SearchQueryHandler' => __DIR__ . '/src/Search/Elasticsearch/SearchQueryHandler.php',
'Search\Elasticsearch\TermRecognizerIndexHandler' => __DIR__ . '/src/Search/Elasticsearch/TermRecognizerIndexHandler.php',
'Search\Exception\Exception' => __DIR__ . '/src/Search/Exception/Exception.php',
'Search\Factory\AutoSuggestQueryHandlerFactory' => __DIR__ . '/src/Search/Factory/AutoSuggestQueryHandlerFactory.php',
'Search\Factory\AutoSuggestServiceFactory' => __DIR__ . '/src/Search/Factory/AutoSuggestServiceFactory.php',
'Search\Factory\DocumentStorerServiceFactory' => __DIR__ . '/src/Search/Factory/DocumentStorerServiceFactory.php',
'Search\Factory\QueueWorkerServiceFactory' => __DIR__ . '/src/Search/Factory/QueueWorkerServiceFactory.php',
'Search\Factory\SearchIndexHandlerFactory' => __DIR__ . '/src/Search/Factory/SearchIndexHandlerFactory.php',
'Search\Factory\SearchQueryHandlerFactory' => __DIR__ . '/src/Search/Factory/SearchQueryHandlerFactory.php',
'Search\Factory\SearchServiceFactory' => __DIR__ . '/src/Search/Factory/SearchServiceFactory.php',
'Search\Factory\SearchSimpleServiceFactory' => __DIR__ . '/src/Search/Factory/SearchSimpleServiceFactory.php',
'Search\Factory\SearchStatistikIndexHandlerFactory' => __DIR__ . '/src/Search/Factory/SearchStatistikIndexHandlerFactory.php',
'Search\Factory\TermRecognizerServiceFactory' => __DIR__ . '/src/Search/Factory/TermRecognizerServiceFactory.php',
'Search\Factory\TermrecognizerIndexHandlerFactory' => __DIR__ . '/src/Search/Factory/TermrecognizerIndexHandlerFactory.php',
'Search\Factory\TermrecognizerQueryHandlerFactory' => __DIR__ . '/src/Search/Factory/TermrecognizerQueryHandlerFactory.php',
'Search\Factory\RequestHandlerFactory' => __DIR__ . '/src/Search/Factory/RequestHandlerFactory.php',
'Search\Logger\LoggerInterface' => __DIR__ . '/src/Search/Logger/LoggerInterface.php',
'Search\Logger\StatisticLogger' => __DIR__ . '/src/Search/Logger/StatisticLogger.php',
'DatabaseQueue' => __DIR__ . '/src/Search/Queue/DatabaseQueue.php',
'Search\Search\QueryWordReducer' => __DIR__ . '/src/Search/Search/QueryWordReducer.php',
'Search\Search\RecognizedTermConsumer' => __DIR__ . '/src/Search/Search/RecognizedTermConsumer.php',
'Search\Search\SearchService' => __DIR__ . '/src/Search/Search/SearchService.php',
'Search\Search\SuggestionListBuilder' => __DIR__ . '/src/Search/Search/SuggestionListBuilder.php',
'Search\Search\Util' => __DIR__ . '/src/Search/Search/Util.php',
'Search\Search\ViewState' => __DIR__ . '/src/Search/Search/ViewState.php',
'Search\Search\ViewStateToSearchRequestTransformer' => __DIR__ . '/src/Search/Search/ViewStateToSearchRequestTransformer.php',
'Search\Search\SearchSimpleService' => __DIR__ . '/src/Search/Search/SearchSimpleService.php',
'Search\AutoSuggester' => __DIR__ . '/src/Search/AutoSuggester.php',
'Search\QueryCleaner' => __DIR__ . '/src/Search/QueryCleaner.php',
'Search\Request' => __DIR__ . '/src/Search/Request.php',
'Search\RequestHandler' => __DIR__ . '/src/Search/RequestHandler.php',
'Search\SearchSource' => __DIR__ . '/src/Search/SearchSource.php',
'Search\Util' => __DIR__ . '/src/Search/Util.php',
'Search\QueueWorker' => __DIR__ . '/src/Search/QueueWorker.php',
'Search\AbstractDocumentStorer' => __DIR__ . '/src/Search/AbstractDocumentStorer.php',
'Search\DocumentStorer' => __DIR__ . '/src/Search/DocumentStorer.php',
'Search\TermRecognizer' => __DIR__ . '/src/Search/TermRecognizer.php',
'Search\Module' => __DIR__ . '/Module.php',
);
Extract from the correlating Module.php:
public function getAutoloaderConfig() {
return [
'Zend\Loader\ClassMapAutoloader' => [
__DIR__ . '/autoload_classmap.php'
],
'Zend\Loader\StandardAutoloader' => [
'namespaces' => [
__NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/', __NAMESPACE__)
]
]
];
}
I checked already that the Autoloader uses the classmap.
EDIT ADDED INFORMATION:
Sorry for the late answer. Right now your app loads for half a second - 0.6s to be precise. So I the autoloader is doing his works. Your queries are also executed fast. There are two more ways I can think of to speed up your applications.
First way - using template map
Locate your templatemap_generator.php file. It should be in your vendor/zendframework/zendframework/bin folder. Navigate to your module folder e.g. Application directory where the src, view, config folders are. Open a terminal and type php ../../vendor/zendframework/zendframework/bin/templatemap_generator.php ZF will create a template map in your module directory. Now to use this template, simply modify your module.config.php file. The file structure is similar to the one from clasmap_autoloader.php
return array(
// Telling where the views are
'view_manager' => array(
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => include __DIR__ . '/../template_map.php', // <-- add this line. You can remove `template_path_stack`
),
In your controllersfor each action add a view template.
public indexAction()
{
$view = new ViewModel();
$view->setTemplate("aplication/index/index");
return $view;
}
Second way - Using module cache in production environment.
Let's say you have this line in your .htaccess - SetEnv APPLICATION_ENV "development"
In your public/index.php file if you haven't done something similar, add this:
/**
* Set global ENV. Used for debugging
*/
if (isset($_SERVER['APPLICATION_ENV']) && $_SERVER["APPLICATION_ENV"] === 'development') {
define("APP_ENV", 'development');
} else {
define("APP_ENV", "production");
}
This will ensure that you have a global env across your application which says if debugging is on or off and it helps you avoid DRY code.
Now from your root folder open config/application.config.php
<?php
$modules = [];
if (APP_ENV === 'development') {
$modules[] = 'ZendDeveloperTools';
$modules[] = 'BjyProfiler';
$modules[] = 'SanSessionToolbar';
}
$modules[] = 'Application';
$modules[] = 'Admin';
return [
// This should be an array of module namespaces used in the application.
'modules' => $modules,
// These are various options for the listeners attached to the ModuleManager
'module_listener_options' => [
// This should be an array of paths in which modules reside.
// If a string key is provided, the listener will consider that a module
// namespace, the value of that key the specific path to that module's
// Module class.
'module_paths' => [
'./module',
'./vendor',
],
// An array of paths from which to glob configuration files after
// modules are loaded. These effectively override configuration
// provided by modules themselves. Paths may use GLOB_BRACE notation.
'config_glob_paths' => [
'config/autoload/{{,*.}global,{,*.}local}.php',
],
// Whether or not to enable a configuration cache.
// If enabled, the merged configuration will be cached and used in
// subsequent requests.
'config_cache_enabled' => (APP_ENV === 'production'),
// The key used to create the configuration cache file name.
'config_cache_key' => md5('app_config'),
// Whether or not to enable a module class map cache.
// If enabled, creates a module class map cache which will be used
// by in future requests, to reduce the autoloading process.
'module_map_cache_enabled' => (APP_ENV === 'production'),
// The key used to create the class map cache file name.
'module_map_cache_key' => md5('module_map'),
// The path in which to cache merged configuration.
'cache_dir' => dirname(__DIR__)."/data/cache",
// Whether or not to enable modules dependency checking.
// Enabled by default, prevents usage of modules that depend on other modules
// that weren't loaded.
'check_dependencies' => (APP_ENV !== 'production'),
],
// Used to create an own service manager. May contain one or more child arrays.
//'service_listener_options' => [
// [
// 'service_manager' => $stringServiceManagerName,
// 'config_key' => $stringConfigKey,
// 'interface' => $stringOptionalInterface,
// 'method' => $stringRequiredMethodName,
// ],
// )
// Initial configuration with which to seed the ServiceManager.
// Should be compatible with Zend\ServiceManager\Config.
// 'service_manager' => [],
];
config_cache_* will activate and cache your route config when your app is in production. All your module routes will be cached. Also If the website is in production the debugging modules will not be loaded.
You can replace md5('app_config') with whatever you want.

phalcon framework webtools not working when creating models, views and controllers

I'm having some problems while trying to get phalcon webtools working.
When using command line devtools I can create controllers and models without problems.
However, things aren't that easy with the webtools.
It correctly shows already created controllers and models:
Controllers (http://i.imgur.com/IRWPaVJ.png)
Models (http://i.imgur.com/rIbvbg9.png)
And I can also edit them (http://i.imgur.com/orJweLl.png).
Apparently, Db connexion is ok, since webtools shows every table in the DB:
Models (http://i.imgur.com/iOkZfyo.png)
Scaffolding (http://i.imgur.com/5ZLRuq5.png)
However, when trying to create a controller from the web interface, I got the next error:
"Please specify a controller directory"
Same when trying to create a Model from a database table :
"Database configuration cannot be loaded from your config file"
Or when trying to generate scaffold :
"Adapter was not found in the config. Please specify a config variable
[database][adapter]"
My app/config/config.php content:
return new \Phalcon\Config(array(
'database' => array(
'adapter' => 'Mysql',
'host' => 'localhost',
'username' => 'phalcon',
'password' => 'phalcon',
'dbname' => 'phalcon',
'charset' => 'utf8',
),
'application' => array(
'controllersDir' => __DIR__ . '/../../app/controllers/',
'modelsDir' => __DIR__ . '/../../app/models/',
'viewsDir' => __DIR__ . '/../../app/views/',
'pluginsDir' => __DIR__ . '/../../app/plugins/',
'libraryDir' => __DIR__ . '/../../app/library/',
'cacheDir' => __DIR__ . '/../../app/cache/',
'baseUri' => '/phalconTest/',
)
));
My public/webtools.config.php content:
define('PTOOLS_IP', '192.168.248.135');
define('PTOOLSPATH', 'C:/phalcon-devtools');
My public/webtools.php:
use Phalcon\Web\Tools;
require 'webtools.config.php';
require PTOOLSPATH . '/scripts/Phalcon/Web/Tools.php';
Tools::main(PTOOLSPATH, PTOOLS_IP);
Im running Phalcon 1.3.4 - Windows x86 for PHP 5.4.0 (VC9)
It seems like a bug in webtools.
Look at vendor/phalcon/devtools/scripts/Phalcon/Builder/Component.php
there is the _getConfig function.
The quick and dirty solution is prepend ../ to path.
You need to change the first line in app/config/config.php
defined('APP_PATH') || define('APP_PATH', realpath('..'));
To add to some of the answers, the editing of configPath by prepending ../ and also some code changes, has forgotten a a little '/' when modelPath has been rtrimmed.
Also, code will be updated and fixed but as of now, one can probably fix the issues by editing your/path/phalcon-devtools/scripts/Phalcon/Builder/Model.php; find
$modelsDir = rtrim(rtrim($modelsDir, '/'), '\\') . DIRECTORY_SEPARATOR;
if ($this->isAbsolutePath($modelsDir) == false) {
$modelPath = $path . DIRECTORY_SEPARATOR . $modelsDir;
} else {
// $modelPath = $modelsDir;
// replace or ADD TO LINE ABOVE so it looks like BELOW:
$modelPath = DIRECTORY_SEPARATOR . $modelsDir;
}
Then Models will work in webtools along with TKF's answer. Enjoy.
Apply changes in webtools.config.php like here:
<?php
if (!defined('PTOOLS_IP'))
define('PTOOLS_IP', '192.168.');
if (!defined('PTOOLSPATH'))
define('PTOOLSPATH', '/path/to/phalcon/devtools');
return array(
'application' => array(
'controllersDir' => __DIR__ . '/../../app/controllers/',
'modelsDir' => __DIR__ . '/../../app/models/',
),
'database' => array(
'adapter' => 'Mysql',
'host' => 'localhost',
'username' => 'usr',
'password' => 'pwd',
'dbname' => 'dbname',
)
);
Somewhat related, I had an issue with the webtools url getting longer and longer .. Eventually I could fix this by adding the word webtools in a replacement for the baseUri in config.php .
<?php ### config.php ... somewhat relevant parts ...
return new \Phalcon\Config([
'database' => [ # ... some things ...
],
'application' => [ # ... some more ...
// This allows the baseUri to be understand project paths that are not in the root directory
// of the webpspace. This will break if the public/index.php entry point is moved or
// possibly if the web server rewrite rules are changed. This can also be set to a static path.
'baseUri' => preg_replace(
'/(public([\/\\\\]))?(index)|(webtools).php$/',
'',
$_SERVER["PHP_SELF"]
),
]
]);

Categories