in my laravel 4.2 projects I use the file ioc.php, to use functions anywhere in my application:
Laravel 4.2 structure
|
|
|app|
|routes.php
|ioc.php <-- place here
My ioc.php content:
<?php
// services class
App::singleton('ApiRpService', function()
{
$config = Config::get('app.web_config.api');
$config['lang'] = Config::get('app.locale');
$config['currency'] = Config::get('app.currency');
$service = new \services\ApiService();
$service -> configure(array_merge($config,Config::get('app.web_config.webs')[$_SERVER['SERVER_NAME']]));
return $service;
});
App::singleton('CartService', function()
{
//die(Config::get('app.web_config.webs.mantaspersonalizadas.es.local'));
$service = new \services\CartService(App::make('ApiRpService'));
return $service;
});
App::singleton('ApiCcService',function(){
$api_cc = new \services\ApiCcService(Config::get('app.web_config.webs')[$_SERVER['SERVER_NAME']]['secret_key_old_cc']);
return $api_cc;
});
// shared cart when head render
View::composer('layouts.header', function($view)
{
$cart_service = App::make('CartService');
$params = array();
$params['cart'] = $cart_service->getCart();
//Controller::call('PagesController#getPromotionData');
App::make('PagesController')->getPromotionData();
# lenguajes extras
$params['extra_langs'] = [];
$extra_langs = array_merge(#Config::get('app.web_config.webs')[$_SERVER['SERVER_NAME']]['lng_extra'],array(#Config::get('app.web_config.webs')[$_SERVER['SERVER_NAME']]['lng_default']));
if (count($extra_langs) > 0){
foreach($extra_langs as $lang)
{
if ($lang != App::getLocale())
{
$route_name = substr(Route::currentRouteName(), 0, strrpos(Route::currentRouteName(),'_')).'_'.$lang;
//die(URL::route($route_name));
$params['extra_langs'][] = array(
'lang' => $lang,
'url' => URL::route($route_name,array('--',Input::get('id','')))
);
}
}
}
$params['web_url'] = Request::root() . (strlen(Request::segment(1)) == 2? '/'.Request::segment(1):'');
//dd($params['promotion_data']);
$view -> with($params);
});
View::composer('layouts.head', function($view)
{
if (App::environment('production'))
$view -> with('g_analytics_id', #Config::get('app.web_config.webs')[$_SERVER['SERVER_NAME']]['g_analytics']['account']);
});
View::composer('layouts.metas', function($view)
{
$params = [];
if (Lang::has('messages.welcome'))
$params['title'] ="";
if (Lang::has('messages.welcome'))
$params['description'] ="";
$view -> with($params);
});
// shared newsletter when footer render
View::composer('layouts.footer', function($view)
{
$api = App::make('ApiRpService');
$view -> with(array(
'token' => $api->getPublicToken(),
'google_plus' => #Config::get('app.web_config.webs')[$_SERVER['SERVER_NAME']]['google_plus'],
'facebook' => #Config::get('app.web_config.webs')[$_SERVER['SERVER_NAME']]['facebook'],
'twitter' => #Config::get('app.web_config.webs')[$_SERVER['SERVER_NAME']]['twitter'],
'chat_online' => #Config::get('app.web_config.webs')[$_SERVER['SERVER_NAME']]['chat_online']
));
});
App::singleton('imghelper', function(){
return new \utils\ImageHelper(Config::get('app.web_config.urlStaticProductsImg'));
});
In Laravel 5 docs not mention the ioc.php...
Where I can place these functions?
Note that these functions are used in all views.
Generally, your individual services should have their own ServiceProvder. These can be placed in any particular directory, and you can register all your service providers in your config/app.php to be automatically loaded and run.
You'll see in your config/app.php that a base Laravel project pre-registers some providers for your commonly used facades like DB.
Just make sure that the names of your service providers follow the PSR-4 standard so that Laravel's auto-loader can correctly resolve the class!
If you're looking for the docs on "IOC" in Laravel 5, it is now called the "Service Container" - here are the docs.
Related
I'm trying to configure routes in my OctoberCMS app. I configure routes in Plugin.php file of my plugin.
At the moment my code:
public function boot()
{
Validator::extend('numeric_for_repeater', function($attribute, $value, $parameters) {
foreach ($value as $v)
{
$validator = Validator::make(
$v,
[
'stock_quantity' => 'sometimes|numeric',
'stock_votes_quantity' => 'sometimes|numeric',
'value' => 'sometimes|numeric',
],
$parameters
);
if ($validator->fails())
return false;
}
return true;
});
\Route::get('/oferty/{id}', function ($id = null) {
$theme = Theme::getActiveTheme();
$path = \Config::get('cms.themesPath', '/themes').'/'.$theme->getDirName();
$this->assetPath = $path;
$offer = new Offer();
return \View::make(self::MAMF_PAGE_DIR . 'oferta.htm', ['offer' => $offer->getOfferById($id)]);
});
}
but I got an error:
View [.var.www.plugins.mamf.mamf2017..........themes.mamf2017.pages.oferta.htm] not found. because by default October expects views files in plugin directory.
How can I render view outside of plugin dir, for ex in themes path like this app/themes/mamf2017/pages/oferta.htm
I guess self::MAMF_PAGE_DIR is full base path your application. for example like
/var/www/vhosts/octdev/themes/responsiv-flat/
In short \View::make need absolute path from root
now it will try to look file with configured extensions for october-cms its .htm. others are .blade and .htm.blade etc ..
so in your case (view)file name is 'oferta.htm' that .(dot) is translated to '/' path separator so just don't use it and just use 'oferta' so it will check all possible values in pages directory
oferta.htm
oferta.blade
oferta.htm.balde
this adding .htm is automatic thing so you just need to provide name of view then it will find and work automatically
\Route::get('/oferty/{id}', function ($id = null) {
$theme = \Cms\Classes\Theme::getActiveTheme();
$path = \Config::get('cms.themesPath', '/themes').'/'.$theme->getDirName();
$this->assetPath = $path;
$offer = new Offer();
return \View::make(base_path() . $path . '/pages/' . 'oferta', ['offer' => $offer->getOfferById($id)]);
});
this is tested and working fine hope this will help you.
if its not working please comment.
In Silex2 I am able to use Twig templates but I want to use the PHP engine of Twig, instead of the Twig syntax. For example this guide describes how to do it for Symfony but not Silex 2.
My Silex index.php looks like:
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__.'/views',
));
$app->get('/', function() use ($app) {
return $app['twig']->render('index.html.php', array(
'name' => 'Bob',
));
});
My index.html.php looks like:
<p>Welcome to the index <?php echo $view->name; ?></p>
When I run the app in the browser and view the source, I see the literal string <?php echo $view->name; ?> which hasn't been executed.
I suspect there may be a Twig config setting to tell it I want to use the PHP style templates. To clarify, if I use the Twig syntax instead, e.g.:
<p>Welcome to the index {{ name }} </p>
Then it works and I see the name Bob, therefore I know this is not a web server or PHP config problem.
This code didnt work for me:
$app['template'] = function($app) use($settings) {
$loader = new \Symfony\Component\Templating\Loader\FilesystemLoader([
BASE_DIR . $settings->templates_path
]);
$nameParser = new \Symfony\Component\Templating\TemplateNameParser();
$templating = new \Symfony\Component\Templating\PhpEngine($nameParser, $loader);
return $templating;
};
though, this is didnt work too:
$app->register(new NS\ViewServiceProvider(), [
'view.path' => BASE_DIR . $settings->templates_path,
]);
ViewServiceProvider:
class ViewServiceProvider implements ServiceProviderInterface
{
public function register(Container $app)
{
$app['view'] = function($app) {
$engine = $app['view.engine'];
$helpers = isset($app['view.helpers']) ? $app['view.helpers'] : array();
$helpers = array_merge($helpers, $app['view.default_helpers']);
$engine->setHelpers($helpers);
return $engine;
};
$app['view.engine'] = function($app) {
return new PhpEngine($app['view.parser'], $app['view.loader']);
};
$app['view.loader'] = function($app) {
$paths = isset($app['view.path']) ? $app['view.path'] : array();
return new FileSystemLoader($paths);
};
$app['view.parser'] = function() {
return new TemplateNameParser;
};
$app['view.default_helpers'] = function() {
return array(
new \Symfony\Component\Templating\Helper\SlotsHelper
);
};
}
}
Both throws an error, that cannot find the view.php file
Using the example from http://twig.sensiolabs.org/doc/advanced.html#creating-an-extension: within my main Slim file that creates the view:
$filter = new Twig_SimpleFilter( 'stripslashes', function ( $string ) {
return stripslashes( $string );
});
$loader = new \Twig_Loader_String();
$twig = new Twig_Environment($loader);
$twig->addFilter($filter);
$app->view($twig);
$app->view()->setData( array(
'nav' => $nav,
'sidenav' => $sidenav,
));
Results in: Call to undefined method Twig_Environment::appendData().
Tried in various ways such as this:
$app->view(new \Slim\Views\Twig());
$app->view->parserExtensions = array(
new \Slim\Views\TwigExtension(),
);
$app->view->addFilter($filter);
but I'm just not understanding how it's supposed to work.
For Slim 3, things have changed. It can be done in one line:
$view->getEnvironment()->addFilter($filter);
But that isn't particularly useful without context, so here is a full sample, based on the example provided at the Slim Framework Website: http://www.slimframework.com/docs/features/templates.html
This code demonstrates adding a filter to encode text with rot13
<?php
// Create app
$app = new \Slim\App();
// Get container
$container = $app->getContainer();
// Register component on container
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('path/to/templates', [
'cache' => 'path/to/cache'
]);
$view->addExtension(new \Slim\Views\TwigExtension(
$container['router'],
$container['request']->getUri()
));
$filter = new Twig_SimpleFilter('rot13', function ($string) {
return str_rot13($string);
});
$view->getEnvironment()->addFilter($filter);
return $view;
};
// Render Twig template in route
$app->get('/rot13/{text}', function ($request, $response, $args) {
return $this->view->render($response, 'rot13.html', [
'name' => $args['text']
]);
})->setName('rot13');
// Run app
$app->run();
And the html file rot13.html contains:
{{text|rot13}}
Point your browser at yourservername/rot13/pineapple and you should see
cvarnccyr
Ah. Just needed this two liner:
$twig = $app->view->getInstance();
$twig->addFilter($filter);
I would like to define the following default behavior on my routes:
Url: myapp.com/mymodule/mycontroller/myaction/q/someTerm/key/someValue/key2/anotherValue
This url should give the dispatcher the following params:
array(
'q' => 'someTerm',
'key' => 'someValue',
'key2' => 'anotherValue'
):
I know it can be easily done by extending the router and implementing my own, but I was wondering if Phalcon has a default flag that switches that approach on by default.
Right now, if I apply the route
':module/:controller/:action/:params' to this URL, I get the following params:
array(
0 => 'q',
1 => 'someTerm',
2 => 'key'
... etc
);
Which is something I don't want.
If the Phalcon router doesn't have a default flag that does this, is there an event that fires immediately before the params become available in the DI's dispatcher in the controller? I would like to manually map them into key=>value pairs at least, before they reach the controller.
Edit: I am now looking into the beforeExecuteRoute event in the controller, should do what I need. But I'd still like it if the router did this automatically - sometimes params aren't in a fixed order, or some of them just disappear (think complex search queries).
You can intercept the 'beforeDispatchLoop' event in the dispatcher to transform the parameters before dispatch the action:
$di['dispatcher'] = function(){
$eventsManager = new Phalcon\Events\Manager();
$eventsManager->attach('dispatch', function($event, $dispatcher) {
if ($event->getType() == 'beforeDispatchLoop') {
$keyParams = array();
$params = $dispatcher->getParams();
foreach ($params as $number => $value) {
if ($number & 1) {
$keyParams[$params[$number - 1]] = $value;
}
}
$dispatcher->setParams($keyParams);
}
});
$dispatcher = new Phalcon\MVc\Dispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
});
Then use the transformed parameters in the controller:
class IndexController extends ControllerBase
{
public function indexAction()
{
print_r($this->dispatcher->getParams());
print_r($this->dispatcher->getParam('key'));
}
}
I'm creating an application that exposes a RESTful API in a module called api. For the other modules I created a little class that returns a Zend_Controller_Router_Rewrite object with custom defined routes:
$router = new Zend_Controller_Router_Rewrite();
foreach ($this->_modules as $module) {
if ($module === 'api') continue;
foreach ($this->_getConfigFiles($module) as $filename) {
$config = new Zend_Config_Ini($filename, 'routes');
$router->addConfig($config, 'routes');
}
}
return $router;
For the default module I have the following route:
[routes]
routes.default_index_index.type = Zend_Controller_Router_Route
routes.default_index_index.route = /
routes.default_index_index.defaults.module = default
routes.default_index_index.defaults.controller = index
routes.default_index_index.defaults.action = index
Now, in my Bootstrap file file I have the following:
$router = Shark_Module_Loader::getInstance()->getRouter();
$frontController->setRouter($router);
$frontController->getRouter()->removeDefaultRoutes();
$apiRoute = new Zend_Rest_Route($frontController, array(), array('api'));
$router->addRoute('rest', $apiRoute);
If I skip adding the rest route everything works fine for the default module, of course. But when I add the RESTful route the routes defined in the router are overridden(?), so the current route in the index action of the index controller of the default module ($this->getFrontController()->getRouter()->getCurrentRoute();) is an instance of Zend_Rest_Route. Thus, when trying to access a custom route defined in on of the route config files, lets say:
...
routes.default_pages_view.type = Zend_Controller_Router_Route
routes.default_pages_view.route = /view/:page
routes.default_pages_view.defaults.module = default
routes.default_pages_view.defaults.controller = pages
routes.default_pages_view.defaults.action = view
...
I get a 404 error saying that the request action (get) is not present.
I already went through the docs and didn't see any hint that suggests this behavior.
Any help and guidance will be appreciated.
There is no way to do this out of the box. (Check out this question)
You need to extend the Zend_Controller_Router_Route class. I've done it like this:
class Mauro_Controller_Router_Route_Method extends Zend_Controller_Router_Route {
protected $_method;
public function __construct($route, $defaults = array(), $reqs = array(), Zend_Translate $translator = null, $locale = null) {
list($this->_method, $route) = explode(' ', $route, 2);
parent::__construct($route, $defaults, $reqs, $translator, $locale);
}
public function match($path, $partial = false) {
$requestMethod = $this->getRequest()->getMethod();
$requestMethod = $this->getRequest()->getParam('method')
? strtoupper($this->getRequest()->getParam('method'))
: $requestMethod;
return $requestMethod == strtoupper($this->_method)
? parent::match($path, $partial)
: false;
}
protected function getRequest() {
return Zend_Controller_Front::getInstance()->getRequest();
}
}
You can then use it like this:
$router->addRoute( new Mauro_Controller_Router_Route_Method( 'GET /view/:page', array( 'controller' => 'pages', 'action' => 'view' ), array( 'page' => '/d+', ) ) );