Laravel - Provider data being requested on all routes - php

I am currently using a Laravel Provider to pass data to a view each time it is called. The App.blade.php includes the blade file if the user is authenticated.
My problem is that at the moment, no matter what view the user is on, it still calls the ViewServiceProvider.php, which doesn't seem very efficient.
I have tried to use #if(view()->exists('home')), but that doesn't seem to have any effect what so ever, and thus, the queries are still called from the ViewServiceProvider.php.
App.blade.php:
#if(!Auth::guest())
#if(view()->exists('home'))
#include('layouts.check')
#endif
#endif
ViewServiceProvider.php:
public function boot()
{
view()->composer('layouts.check', function ($view) {
$sites = Site::where('trust_id', Auth::id())->get();
$view->with(['sites' => $sites]);
});
}
Any help would be hugely appreciated.

The problem with you code is that it's check to see if the view exists. Chances are, the view "home" will always exist, so it will always include your view; "layouts.check".
Unless, of course, the view "home" is dynamic and is only there conditionally, which doesn't seem right. If you want the "layouts.check" view file to only load on certain pages, you might want to try "Request::is()".
#if(Request::is('home'))
#include('layouts.check')
#endif

The view composer is going to be called whenever your 'layouts.check' view is rendered.
Even though you've attempted to not have it rendered (by adding in your if statements), the view is still going to be rendered, and your view composer is still going to be called.
The template engine is going to parse your view in one pass. The engine doesn't care about any type of logic inside you're view, it's only job is to convert that logic into PHP code. So, even though you have the statement #if(!Auth::guest()), the parser doesn't understand the actual logic, it just knows to convert that to <?php if (!Auth::guest()) { </php>.
Basically, your #if statements aren't preventing the engine from parsing your include file, it is the parsed PHP code that prevents the results of the include file from showing in your output. So, since your #include file is parsed, the view composer is called.

Related

Laravel - how can make dynamic content with layout?

I'm wanting to create a website with laravel framework. I had made layout but now, have some zone i don't know how to set content for it. Ex: 2 zone of me are left-menu and cart (please view picture). My left-menu will get content from table: categories and cart will get content from package cart [Cart::content()].
It's on layout and of course, all page will have it. But i don't know how to give content of categories and cart() for it. Please help me
I think that you should to use View Composer.
https://laravel.com/docs/5.6/views#view-composers
Use Blade templates, as found here: https://laravel.com/docs/5.6/blade
Wherever in your page you want to print content, use the {{ $mycontent }} construct. You can also use confitionals and loop structures like #if and #foreach to loop through collections.
Then, in your controllers, you can just call the view and pass it content from your database or wherever you get it by doing something like:
return response()->view(“myView”, [“mycontent” => $content], $httpStatus);
You may opt for afterMiddleware if you want it on every page. Create a section on the master blade page (usually app.blade.php) and fill it in the middleware just like you would in any other controller. You can create a middleware by running php artisan create:middleware Cart. A file will be created at app/Http/Middleware/Cart.php.
Register the middleware in the app/Http/kernel.php file.
You may have to add a Auth::check() condition to avoid errors.

Dealing with Views in Phalcon Controllers

I am working on a newly created Phalcon project, and I don't really know how to actually use multiples views.
What is the entry point? I don't really know when each method in the controller is called, under which conditions, etc.
Where is the control flow defined? is it based in the name of the view? or is there a place where you can register them?
Phalcon is a bit different than other well-known PHP frameworks, in that not much is pre-configured or pre-built by default. It's quite loosely-coupled. So you have to decide where and how your control flow will work. This means that you will need to dig deeper in the documentation and also that there could be different way to achieve the same thing.
I'm going to walk you through a simple example and provide references, so you can understand it more.
1) You would start by defining a bootstrap file (or files) that will define the routes, or entry points, and will setup and create the application. This bootstrap file could be called by an index.php file that is the default file served by the web server. Here is an example of how such bootstrap file will define the routes or entry points (note: these are just fragments and do not represent all the things that a bootstrap file should do):
use Phalcon\Di\FactoryDefault;
// initializes the dependency injector of Phalcon framework
$injector = new FactoryDefault();
// defines the routes
$injector->setShared('router', function () {
return require_once('some/path/routes.php');
});
Then it the routes.php file:
use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Group as RouterGroup;
// instantiates the router
$router = new Router(false);
// defines routes for the 'users' controller
$user_routes = new RouterGroup(['controller' => 'users']);
$user_routes->setPrefix('/users');
$user_routes->addGet('/show/{id:[0-9]{1,9}}', ['action' => 'show']);
$router->mount($user_routes);
return $router;
Im defining routes in an alternate way, by defining routes groups. I find it to be more easy to organize routes by resource or controller.
2) When you enter the url example.com/users/show/123, the routes above will match this to the controller users and action show. This is specified by the chunks of code ['controller' => 'users'], setPrefix('/users') and '/show/{id:[0-9]{1,9}}', ['action' => 'show']
3) So now you create the controller. You create a file in, let's say, controllers/UsersController.php. And then you create its action; note the name that you used in the route (show) and the suffix of Action:
public function showAction(int $id) {
// ... do all you need to do...
// fetch data
$user = UserModel::findFirst(blah blah);
// pass data to view
$this->view->setVar('user', $user);
// Phalcon automatically calls the view; from the manual:
/*
Phalcon automatically passes the execution to the view component as soon as a particular
controller has completed its cycle. The view component will look in the views folder for
a folder named as the same name of the last controller executed and then for a file named
as the last action executed.
*/
// but in case you would need to specify a different one
$this->view->render('users', 'another_view');
}
There is much more stuff related to views; consult the manual.
Note that you will need to register such controller in the bootstrap file like (Im also including examples on how to register other things):
use Phalcon\Loader;
// registers namespaces and other classes
$loader = new Loader();
$loader->registerNamespaces([
'MyNameSpace\Controllers' => 'path/controllers/',
'MyNameSpace\Models' => 'path/models/',
'MyNameSpace\Views' => 'path/views/'
]);
$loader->register();
4) You will also need to register a few things for the views. In the bootstrap file
use Phalcon\Mvc\View;
$injector->setShared('view', function () {
$view = new View();
$view->setViewsDir('path/views/');
return $view;
});
And this, together with other things you will need to do, particularly in the bootstrap process, will get you started in sending requests to the controller and action/view defined in the routes.
Those were basic examples. There is much more that you will need to learn, because I only gave you a few pieces to get you started. So here are some links that can explain more. Remember, there are several different ways to achieve the same thing in Phalcon.
Bootstrapping:
https://docs.phalconphp.com/en/3.2/di
https://docs.phalconphp.com/en/3.2/loader
https://docs.phalconphp.com/en/3.2/dispatcher
Routing: https://docs.phalconphp.com/en/3.2/routing
Controllers: https://docs.phalconphp.com/en/3.2/controllers
More on Views (from registering to passing data to them, to templating and more): https://docs.phalconphp.com/en/3.2/views
And a simple tutorial to teach you some basic things: https://docs.phalconphp.com/en/3.2/tutorial-rest
The application begins with the routing stage. From there you grab the controller and action from the router, and feed it to the dispatcher. You set the view then call the execute the dispatcher so it access your controller's action. From there you create a new response object and set its contents equal to the view requests, and finally send the response to the client's browser -- both the content and the headers. It's a good idea to do this through Phalcon rather than echoing directly or using PHP's header(), so it's only done at the moment you call $response->send(); This is best practice because it allows you to create tests, such as in phpunit, so you can test for the existence of headers, or content, while moving off to the next response and header without actually sending anything so you can test stuff. Same idea with exit; in code, is best to avoid so you can write tests and move on to the next test without your tests aborting on the first test due to the existence of exit.
As far as how the Phalcon application works, and in what steps, it's much easier to follow the flow by looking at manual bootstrapping:
https://docs.phalconphp.com/en/3.2/application#manual-bootstrapping
At the heart of Phalcon is the DI, the Dependency Injection container. This allows you to create services, and store them on the DI so services can access each other. You can create your own services and store them under your own name on the DI, there's nothing special about the names used. However depending on the areas of Phalcon you used, certain services on the DI are assumed like "db" for interacting with your database. Note services can be set as either shared or not shared on the DI. Shared means it implements singleton and keeps the object alive for all calls afterwards. If you use getShared, it does a similar thing even if it wasn't initially a shared service. The getShared method is considered bad practice and the Phalcon team is talking about removing the method in future Phalcon versions. Please rely on setShared instead.
Regarding multiple views, you can start with $this->view->disable(); from within the controller. This allows you to disable a view so you don't get any content generated to begin with from within a controller so you can follow how views work from within controllers.
Phalcon assumes every controller has a matching view under /someController/someView followed by whatever extension you registered on the view, which defaults to .volt but can also be set to use .phtml or .php.
These two correspond to:
Phalcon\Mvc\View\Engine\Php and Phalcon\Mvc\View\Engine\Volt
Note that you DON'T specify the extension when looking for a template to render, Phalcon adds this for you
Phalcon also uses a root view template index.volt, if it exists, for all interactions with the view so you can use things like the same doctype for all responses, making your life easier.
Phalcon also offers you partials, so from within a view you can render a partial like breadcrumbs, or a header or footer which you'd otherwise be copy-pasting into each template. This allows you to manage all pages from the same template so you're not repeating yourself.
As far as which view class you use within Phalcon, there's two main choices:
Phalcon\Mvc\View and Phalcon\Mvc\View\Simple
While similar, Phalcon\Mvc\View gives you a multiple level hierarchy as described before with a main template, and a controller-action based template as well as some other fancy features. As far as Phalcon\Mvc\View\Simple, it's much more lightweight and is a single level.
You should be familiar with hierarchical rendering:
https://docs.phalconphp.com/en/3.2/views#hierarchical-rendering
The idea is with Phalcon\Mvc\View that you have a Main Layout (if this template exists) usually stored in /views/index.volt, which is used on every page so you can toss in your doctypes, the title (which you would set with a variable the view passed in), etc. You'd have a Controller Layout, which would be stored under /views/layouts.myController.volt and used for every action within a controller (if this template exists), finally you'd have the Action Layout which is used for the specific action of the controller in /views/myController/myAction.volt.
There are all types of ways you can break from Phalcon's default behavior. You can do the earlier stated $this->view->disable(); so you can do everything manually yourself so Phalcon doesn't assume anything about the view template. You can also use ->pick to pick which template to use if it's going to be different than the controller and action it's ran in.
You can also return a response object from within a controller and Phalcon will not try to render the templates and use the response object instead.
For example you might want to do:
return $this->response->redirect('index/index');
This would redirect the user's browser to said page. You could also do a forward instead which would be used internally within Phalcon to access a different controller and/or action.
You can config the directory the views are stored with setViewsDir. You can also do this from within the controller itself, or even within the view as late as you want, if you have some exceptions due to a goofy directory structure.
You can do things like use $this->view->setTemplateBefore('common') or $this->view->setTemplateAfter('common'); so you can have intermediate templates.
At the heart of the view hierarchy is <?php echo $this->getContent(); ?> or {{ content() }} if you're using Volt. Even if you're using Volt, it gets parsed by Phalcon and generates the PHP version with $this->getContent(), storing it in your /cache/ directory, before it is executed.
The idea with "template before" is that it's optional if you need another layer of hierarchy between your main template and your controller template. Same idea with "template after" etc. I would advise against using template before and after as they are confusing and partials are better suited for the task.
It all depends on how you want to organize your application structure.
Note you can also swap between your main template to another main template if you need to swap anything major. You could also just toss in an "if" statement into your main template to decide what to do based on some condition, etc.
With all that said, you should be able to read the documentation and make better sense of how to utilize it:
https://docs.phalconphp.com/en/3.2/api/Phalcon_Mvc_View

Unable to load controllers from another controller

I'm trying to load a controller inside another controller.
$data['com_top_menu'] = $this->load->controller('account/com_top_menu');
However, this seems to not work when I'm trying to load a controller that is located in the same folder as the controller I'm loading it from.
Tried loading controllers from other folders and seem to not load as well. It seams to load only from the 'common' controllers folder.
Edit:
Actually it seems that the controller is loading. If I place an echo in the middle of the loaded controller it will show the output before the template rendered. So, it looks like the controller is loaded and just doesn't output anything through the rendered view, unless it is a controller inside the common folder.
Files are all in place, controller loads, it just doesn't output anything through the view.
Few things for to load controllers-
1st - you can only load controller from same folders (admin/ catalog).
2nd - you can load controller from any subfolder, just need to pass correct loading path.
3rd - If Opencart hasn't that file than it will not display any error, result will be null/ false.
4th - If you are defining any function name then it will call that function else will call index function so in your case index.
5th - Please use this
return $this->load->view('your.tpl', $data);
Instead of
$this->response->setOutput($this->load->view('your.tpl', $data));
6th - Please enable your debug mode from php/ admin so that you will know any error if your code is throwing. Clear your error.log and then try to load controller.
7th - If these all points are code is not working then do 1 thing - add a blank controller with index function and just add one line so that you can return it's result from view then just
echo 'here';
In your view. If OC is not returning this result it's mean you have error in Opencart files else there is error in your code.
You can say these are same in a way (i am not saying completely and don't want to hurt anyone feelings ;)) but this code
$this->load->controller('account/com_top_menu');
is equal to (based on your autoloader)
$obj = new ComTopMenu; //assuming your class name
$data['com_top_menu'] = $obj->index();
so for your solution please check
- you have file com_top_menu.php in your catalog > controller > account >
- your file class name must be ControllerAccountComTopMenu (or any uppercase or lowercase combination but without _)
- your class must have index function because in your case it calling index.

Laravel - How to NOT use a layout

I'm using laravel with controllers layout. But there are some parts of my app where I don't want to use a layout (for example, when returning data to the payment gateway request, for wich I send XML data). I just want to pass data to my view and render it alone, with no need for a layout.
How can I do that? I've been trying some approaches but none worked for this. I can successfuly change what layout to render, but I can't set to render the view without a layout.
Thanks!
Edit: Let me explain it better
My default layout is set in Base_Controller. Then all my controllers extends it but in one of them I need no layout, as I told above. Maybe I need to unset the default layout or something like that, I'm not sure.
You can simply return something from your controller action to bypass the layout.
function get_xml($id) {
$user = User::find($id);
return View::make('user.xml', $user);
}
On your controller functions, you can simply return a string, which will be thrown back to the browser as-is. Alternatively, you can craft a Laravel\Response object, which will allow you to fine-tune your site's output a lot more than just returning a string.
The Response class has a few tricks up its sleeve that are not mentioned on the docs: default return, JSON, forced download.
You're more interested in the first one, which will allow you to correctly set the content-type of the response to application/xml. In addition to this, you can still use views for XML! Generate the view as you would with View::make, but instead of directly returning it, store it in a variable. To render it, call render() on it - it will return the output.
A simple way....
suppose there is a main layout
<body>
#yield('content')
</body>
This content will be where the view will be inserted.
Now,
if you want to use layout, Make the view page like this:
#layout('main')
#section('content')
blah blah your content
#endsection
If you don't want to use layout, omit the codes above.
In controller, the code will be same for both the files.
return View::make('index');

How to get part of the page from other controller

My site I have some content can be voted (+/-). It is working fine now, when all content has its own voter.
Now I'm looking for a way to create a single voting bundle with a entity(votedModel,votedId, user, vote).
Basically the bundle is ready. My problem is how to use it. I'd like to be able to do something like:
class ... extends Controller {
function showAction(Request $request,$id) {
...
$voter=new Voter('myCOntentType',$id,$userid);
...
return $this->render('...', array('voter'=>$voter->getVoter(),...))
}
}
getVoter() would create the voter view.
but I'm stacked how exactly start. I tried to call for the other controller in this manner, but can't create the voter form.
It worked with $voter=$this->forward('VoterbundleNewAction', array('id=>$id,'user'=>$user)->getContent();But this wasn't I had in mind.
I think my approach is all wrong and I may need to do this as service. I cant find my way around.
You can use include or render in your twig template to get other templates' output. So you could create a template (say, voter.html.twig) that contains the HTML for your voting system, and in the Twig, in any place where you need a voter, you could use:
{% include "AcmeVoterBundle:Voter:voter.html.twig" %}
or
{% render "AcmeVoterBundle:Voter:voter" with {"item": item} %}
In the first example, you simply include another template (see also: http://symfony.com/doc/current/book/templating.html#including-other-templates), in the latter situation you actually execute another action method of a controller and the output of that is put into your current template (see also: http://symfony.com/doc/current/book/templating.html#embedding-controllers)

Categories