I'm creating a web app without any framework and I need a route. So i found AltoRoute as interesting solution. But I really don't understand how this working, I have read the documentation page but I have some question to ask. Hope that some one could help. I'll organize the question in step for more precision:
How can I import the controllers?
my app structure look like this:
PUBLIC HTML
App_name
APPLICATION
CONTROLLERS
LIBRARIES
MODELS
VIEW
SYSTEM 'in this folder I have inserted altoroute
I have all the controllers and the php backend inside the application folder. I want import all controllers available in controllers folder in AltoRouter. I tried with this:
require "AltoRouter.php";
$router = new AltoRouter();
$router->setBasePath("/App_name/system");
$router->map("GET|POST", "../application/controllers/backend.php");
is this good for import the controller?
How I can call specific function of the controller loaded?
In the past when I use CodeIgniter I perform this operation for load a function inside the controller:
$this->load->model('backend');
$this->backend->anon_function($foo); // call my personal function inside the controller
how I can do this when I loaded the controllers from AltoRouter?
How I can perform an Ajax call from javascript?
the good thing of the route is this, call a function inside the controller from javascript, in the past with CodeIgniter I use:
$('#login-form').submit(function(event)
{
var postUrl = GlobalVariables.baseUrl + 'user/ajax_check_login';
var postData =
{
'username': $('#username').val(),
'password': $('#password').val()
};
$('.alert').addClass('hidden');
$.post(postUrl, postData, function(response)
{
so how you can see I call ajax_check_login available in the user controller.
So, someone could help me to understand better all this steps? I'm new on route, so I need very an help to understand this..
Related
This may be a dumb question, but I've started exploring Laravel Breeze with vue and I'm not sure how to manage resources and their views. (Using Laravel 9)
For example, if I have a table 'members' and a resource controller 'MemberController', ordinarily in the web.php file I would do something like:
Route::resource('members', MemberController::class)->names('members');
Then I'd create a 'member' folder in my resource/views folder to store the views for that table. I could then call the view from the MemberController something like:
public function index()
{
$members = Member::all();
return view('member.index', compact('members'));
}
I'm trying to do something similar using vue in breeze, so I guess I'd have the vue pages in the 'resources/js/Pages' folder. But this didn't seem to work properly.
I don't know how to transition from the previous approach of handling resources and views to Breeze using vue.
What's the recommended way to handle resources in an SPA with Breeze/vue?
After following Djave's suggestion, I took a look at the sample app from inertia.js and that answered everything.
The problem I had was due to using the dot notation when specifying the path to the vue page. So, in my example above, it should instead be like this:
return view('Member/Index', compact('members'));
The inertia sample app code has a lot of good examples!
This is my long quest to develop web apps using core PHP and follow the best possible practices and not using a framework. I have achieved many things by structuring my project a better way. However ...getting a clean URL is often a problem for large apps.
Till now...I have used the Slim Framework only for creating RESTFUL services outside my web apps.
I am using Slim Framework to create APIs for a PHP project. Now, I have an install of Slim up and running fine. I have my routes talking to the database and doing what they're supposed to do, generally. My question has to do with modularizing the code. At the moment, all my routes are defined in my index.php file in the root directory. I would very much like to separate these out, say into a /controllers folder.
As I liked the way Slim makes pretty good URLs...I am wondering if it is possible to use Slim as my app architecture ...and let all my pages or APIs be accessible through the Slim index.php.
Yes pretty easily here are the steps I have taken on a recent project.
First lets say your have a HomeActionController
class HomeActionController {
//The below line I have moved into an abstract Controller class
public $view = null;
//This is using Slim Views PhpRenderer
//This allows for a controller to render views can be whatever you need
//I did not like the idea of passing the whole DC it seemed overkill
//The below method I have moved into an abstract Controller class
public function __construct(\Slim\Views\PhpRenderer $view = null){
if($view != null){
$this->view = $view;
}
}
//View could be any action method you want to call it.
public function view(Request $request, Response $response, array $args){
$data['user'] = "John Doe";
return $this->view->render($response, 'templates/home.php', $data);
}
}
Now you need to be able to call an instance of this controller from a route so you need to add the controllers you have to the DC
Where ever you are creating your instance of slim you will need to get the DC and add an instance of your controller:
$app = new \Slim\App($config['slim']);
// Get Dependency Container for Slim
$container = $app->getContainer();
$container['HomeActionController'] = new Controller\HomeActionController($container['view']); //Notice passing the view
As a note the above instantiations could have been a closures but I did not see the point at the time or making them. Also, there are ways to lazy load that I have not explored yet see here for more information.
Now the last thing you need to do is be able to call these on the routes which is not a huge challenge.
$app->get('/home', 'HomeActionController:view');
Granted you cannot have an action with parameters but I have not had an issue just passing them along in the request and then getting them from there.
If you want to create a app with no framework, then i would recommend looking through this small github repo:
https://github.com/PatrickLouys/no-framework-tutorial
It goes through with you settings everything up in terms of routing, plus would make everything go through the index.php in a public folder like your asking.
I have an existing application that Im moving to Angular and I have some questions. My new Angular app has four routes:
Home
Activity
Login
Signup
In my old app I had AJAX calls to PHP that would query MySQL and return the information as needed, but I could tie everything together using jQuery and call my AJAX calls from one centrally located .js file.
Now, I need to write a call to $HTTP to do the same thing as my AJAX calls did, but I dont know where to put everything!
For example I have the following sample $HTTP function I found online:
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("users.php")
.then(function(response) {
$scope.users = response.data;
});
});
</script>
Where does this go in the Angular file structure? I intend to call it from the Activity route, which creates another question. Since the route pages are based on templates how do I call the function from the route or template so I can see the results on the Activity page?
Factory/Service is what you are looking for. Ajax call should be made inside a factory method which in turn returns the data to the controller (myCtrl in your example).
You should bind your controller (myCtrl) with the view (Activity) in the route provider itself.
Here is an example that will give you a clear picture.
How factory works
Here i was i have :
A RESTful Symfony API that i created with few bundles
A front AngularJS that i have in the web repository
Now here is a sample of my routing file :
$routeProvider.
when('/liste-produits', {
templateUrl: '../templates/list-products.html',
controller: 'ProductListCtrl'
}).
otherwise({
redirectTo: '/'
});
The fact that i have to use "../". Because otherwise it won't work in dev environnement (app_dev.php). And of course by the time i will post it in production (app.php) i won't need to add this "../"
Do you guys understand my problem ?
Since i can get assetic from Symfony work in the routing file.
How can i solve this ?
There is an approach, where you define a global variable in your base twig file:
Symfony 2:image paths in javascript file with assetic which you can in turn use in e.g. AngularJS.
There is also a bundle called FOSJsRoutingBundle, it sort of exposes your routes to the client and thus javascript. That might be interesting for you.
However there is another option; - I have personally used the approach posted by Rein Baarsma with the twig file and then cached the resulting javascript.
It's fairly simple to write a request listener that renders the twig file to a javascript file once a day or whenever the javascript file is deleted.
I used the same approach with the stylesheets for a project with daily changing colors.
If you do not cache it, the browser will revisit the route returning the javascript on each page and rerender the javascript file, which adds a lot of overhead.
You could simply make a Symfony Controller with a view on a js file. That way you can use the twig (or php) template functions (like twig's path() function) to avoid any strange urls.
In your controller:
public function routingAction(Request $request) {
$this->render('angular/routing.twig.js');
}
And in your routing
$routeProvider.
when('/liste-produits', {
templateUrl: {{ path('product_list') }},
controller: 'ProductListCtrl'
}).
otherwise({
redirectTo: '/'
});
Is it generally a good idea to interact with database in view layer in MVC frameworks?
I'm using Laravel 4.
I want to show some data from database at top of all website's pages.
I have a main.blade.php and: #include("inc.header")
If I should, how can I connect to database from inc/header.php in right way?
I don't want make multiple connections one here at header.php and one in my pages controllers.
I'm more familiar with PDO than Laravel's database methods and ORMs.
Any advice is appreciated!
Edit
Friends gave nice advice and answers about MVC and Laravel workflow, but my main concern is still here.
Ok I have used controllers and models to get required data, then as I said, it should be present for the view layer in every page, So should I repeat the same task to get the same data in All my controllers' actions? (I guess that's why we have Filters here! then again, is it ok to use db in Laravel filters? using a model?)
Thanks in advance :)
Never do anything more than loop thru your data in your view layer. Basically a normal MVC pattern in laravel could be something like this:
It all begins with the routing layer (which btw. is fantastic in laravel)
Using closures
Route::get('/home', function()
{
//Here data is an array, normally you would fetch data
//from your database here and pass it to the View.
$data = array('this', 'is', 'my', 'data-array');
return View::make('my.view')->with(compact('data');
});
Using controllers (and a controller method)
//the same route is bound to a controller method
Route::get('/home','HomeController#myFunction');
The controller for the above could look something like this:
<?php
class HomeController extends BaseController {
//The function you call from your route
public function myFunction()
{
$data = array('this', 'is', 'my', 'data-array');
return View::make('my.view')->with(compact('data');
}
}
The above example just shows the VC in MVC, but generally you pass data from your models in the same way.
Heres a quick one:
Model usage in controllers
public function myFunction($user)
{
$userdata = User::find($user)->orderBy('firstname', 'desc');
$infodata = Event::find(1)->course;
return View::make('my.view')->with(compact('data', 'infodata');
}
So the idea is that laravel lets you do things in multiple ways. If you have a minor app, and are sure that you can manage without controllers you could skip the controller and keep everything in your routing layer.
For most apps however the controllers are needed for controlling the dataflow in the application.
If you are totally new to MVC you should check out some tuts on the subject.
EDIT:
Ahaa! So you wanted to share some piece of data in all your views! Well thats simple. Because all your controllers extend the BaseController you can simply pass in the data in there. Like so:
class BaseController extends Controller {
public function __construct()
{
$data = array('alot', 'of', 'data');
return View::share('data', $data);
}
}
Now the data variable is available in all the views.
PS. Filters are meant to filter stuff, like to check if certain things are "ok". This could include to check authed users, or form submissions etc.
There is another solution that is especially handy for cases like yours. If you have 15 routes that all ultimately include the inc.header view... well you can see where this is going. You'll have data logic repeated in several places. Patrik suggested using the BaseController which is a good solution but I prefer to use a composer.
View::composer('inc.header', function ($view)
{
$view->some_data = MyModel::where(...)->get();
});
It doesn't get much easier then that. :)
Is it generally a good idea to interact with database in view layer in MVC frameworks?
No, you don't interact with your database (model) in your view layer. MVC stands for "Model View Controller" to separate logic, application data and business rules of your application.
If I should, how can I connect to database from inc/header.php in right way?
I don't want make multiple connections one here at header.php and one in my pages controllers.
You could create a main layout (containing your header) and use this layout for all the pages of your application:
app/views/
layouts/main.blade.php
page1.blade.php
layouts/main.blade.php:
<html>
<head>...</head>
<body>
<div>Your header that will be included in each of your pages</div>
<!-- The content of the current page: -->
#yield('body')
</body>
</html>
page1.blade.php:
#extends('layouts.main')
#section('body')
<div>The content of your page</div>
#stop
Learn more about the Blade templating engine.
Now where do you fetch your data?
The fastest/easiest way to develop is to use the routes as Controllers and as your application evolves you start refactoring your code and create Controllers.
app/routes.php:
Route::get('page1', function(){
//Fetch your data the way you prefer: SQL, Fluent or Eloquent (Laravel ORM)
//$data = DB::select('select * from yourtable');
$data = YourModel::all();
//Pass your data to the view
return View::make('page1')
->with('data', $data);
});
The data can be fetch using Fluent class or Eloquent ORM.
I suggest you to learn the basics of Laravel to properly create the base of your application so it will be really easy to maintain in the future.
The answer and issue here is not so simple. First have just been introduced to MVC and trying to understand the basic concept, the flow for MVC is Controller->Model->View. Here we see that the data is passed from the model directly to the View. The current examples of how to use Laravel MVC is to have the Model return data to controller making the flow as follows: Conntroller->Model-Controller->View. Here we see that the model and view are not aware of each other. A qucik look on wikipedia show that this type of modeling and controlling is know has MVA. The A is for adapter and also known as mediating controller, so now we are back to the answer here. Should we be using MVA or MVC? How would one achieve true MVC in Laravel? Answer is to use {{Form:model}} facade for true MVC. But then what happens if the view changes? should we be calling model from the view to get the new data? Answer is no, if the view has to change then user should have caused a controller to react kicking off a new cycle of MVC. So what we can see here a mix of MVC and MVA using the Laravel framework, can achieve a highly customized flow based on the needs of the site.