"how to load classes based on pretty urls in mvc-like page?" Code Answer
Answers related to “how to load classes based on pretty urls in mvc-like page?”
- how to run php code on submit button without refreshing/ reloading the page
- How to update content based on user actions [like the facebook wall]
- How to load routes based on application/json header in Laravel
- Send email to multiple recipients based on selected option in php?
- How to display images based on their distance to the center image?
- how to assign id based on array values
- How to sort files based on the last upload time?
- How to delete data based on value in session variable
- How to format dates based on locale?
- How to load file into mysql DB on a shared hosting platform?
- How to redirect users based on random URL string?
- How to merge array based on their key by value in php?
- How to hide columns based on condition in yii2 gridview?
- Codeigniter - How to route controller based on whether a subdomain exists or not
- how to load xml from this code please
- EmberJS: How to load multiple models on the same route?
- How to load Classes at runtime from a folder or JAR?
- Load images based on dynamic path in ReactJs
- Rails 3.1 asset pipeline: how to load controller-specific scripts?
- How to mock the Request on Controller in ASP.Net MVC?
- How to convert View Model into JSON object in ASP.NET MVC?
- How to load Assembly at runtime and create class instance?
- How to validate file type of HttpPostedFileBase attribute in Asp.Net MVC 4?
- How to use permission_required decorators on django class-based views
- How to clear browser cache on browser back button click in MVC4?
- How to set a CheckBox by default Checked in ASP.Net MVC
- How to display an image from a path in asp.net MVC 4 and Razor view?
- How to implement Permission Based Access Control with Asp.Net Core
- How to replace the default ModelState error message in Asp.net MVC 2?
- How to map dynamic url /prj/noticeOpen/2 in Spring MVC controller
- How to simplify my statefull interlaced modal dialogs in ASP.NET MVC
- How to install feature based on the property set in custom action?
- ASP.NET MVC: How to automatically disable [RequireHttps] on localhost?
- How to load external html into a div?
- How to filter rows based on difference in dates between rows in R?
- how to know if the request is ajax in asp.net mvc?
- How to load navigation properties on an IdentityUser with UserManager
- android: how to load xml file from assets directory?
- How to download a file through ajax request in asp.net MVC 4
- XPath: How to select elements based on their value?
- How to do role based authorization for asp.net mvc 4 web api
- How to perform periodic work on an ASP.NET MVC website?
- Python: How to load a module twice?
- How to start WPF based on Arguments
- How to load vendor asset folder in Rails 4?
- Are there tags to specify the Google +1 story format in Google+ like og-meta for Facebook?
- How to delete row based on cell value
- jQuery how to load some json records into a form fields?
- How to load first x items and give user the option to load more in MVC.NET
- How to integrate stripe payment with custom form in ASP.NET MVC?
- How to rbind matrices based on objects names?
- How to filter DataView based on multiple inputs
- How to find processes based on port and kill them all?
- How to add line based on slope and intercept in Matplotlib?
- How to change the login and signup urls in devise plugin Rails
- How to return multiple values from a function in Kotlin like we do in Swift?
- Pandas: How to sum columns based on conditional of other column values?
- How to get current_app for using with reverse in multi-deployable reusable Django application?
- How to set different Timeouts for different URLs in ASP.NET
- How to exclude classes from the coverage calculation in EclEmma without actually excluding them from the coverage...
- How to sort dataframe based on a column in another dataframe in Pandas?
- How to download a file using web api in ASP.NET MVC 4 and jquery
- How to close the radwindow on serverside and refresh the parent page
- How to Implement Single Sign On in MVC4
- How to load all views in UITabBarController?
- How to draw Chart based on DataTable from console application?
- How to render file in Rails 5 API?
- How to create table based on JDBC Result Set
- How to load correct version of dynamic libraries and gems (libxml, Nokogiri) within a custom Rails engine gem?
- Excel VBA, How to select rows based on data in a column?
- in R shiny, how to automatically or based on function tabPanel, given we have 3 levels of lists?
- How to extract text based on font color from a cell with text of multiple colors
- How to filter data based on one word of a column value?
- Symfony2 - how to create form based on dynamic parameters from db? (EAV)
- How to get Form data as a Map in Spring MVC controller?
- ASP.NET MVC: Masterpage: How to set css class on active menu item
- How to access HttpContext inside a unit test in ASP.NET 5 / MVC 6
- How to restart id counting on a table in PostgreSQL after deleting some previous data?
- How to integrate OpenId with ASP.Net Membership in MVC
- How to login with “UserName” instead of “Email” in MVC Identity?
- How to load an ImageView from a png file?
- Razor syntax to render section based on condition
- How to ConfigureServices Authentication based on routes in ASP.NET Core 2.0
- How to parse sentences based on lexical content (phrases) with Python-NLTK
- Load class based on SDK version
- How to load nested classes in Java?
- How to loop through two viewbag items on View pages in MVC 4.0
- Rails & Ransack - Sorting/searching based on a definition in the model
- How to filter IEnumerable based on an entity input parameter
- How to get visitor IP on load balancing machine using asp.net
- How to sort documents based on length of an Array field
- How to move MKMapView based on selected annotation
- How can I create a generic view model in MVC?
- How to load second selectOneMenu on change of first selectOneMenu?
- How to get Microsoft.AspNet.Http.HttpContext instance in Class Constructor using DI
- How to localize the Controller names and actions in an ASP.NET MVC application?
- How to boost search based on index type in elasticsearch or lucene?
- How to respond conditionally based on the request when using netcat
- how to plug a TCP-IP client server in a spring MVC application
- How to add DbContext based on environment in ASP.net Core
- How to load a pdf on android from a url?
- How to filter data based on condition using non array formula
- How to check header files and library functions in CMake like it is done in Autotools?
- how to load a Javascript file to rails html erb
- How to pass a list of id's in a AJAX request to the Server in MVC
- How to hide footer layout on a particular page?
- using DI to load repository instance on each mvc request
- How to disable binding of the route values in ASP.NET MVC?
- adding or removing classes based on route changes in angular
- How to filter documents based on an embedded array?
- How to read the data from a dropdown in ASP.Net MVC 3
- How to drop columns based on multiple filters in a dataframe using PySpark?
- How to populate a textbox based on dropdown selection in MVC..?
- in R, how to automatically plots based on lists?
- .NET Core 3.1 web application with React - how to prevent access based on Active Directory group
- jqGrid & ASP.NET 4 MVC: How to make search implementation on a DBContext repository and 'calculated' properties?
- How to use partial view from another project in asp.net mvc
- How to sort HashMap based on Date?
- How to select route based on header in Zuul
- c# webcontrol - how to load a html on the fly?
- How to load MVC Partial View and keep Angular JS working
- How to open another tab on click without refresh current page in ASP.NET Web Forms?
- How to make a select list item selected in asp.net mvc?
- How to properly configure Stomp and SockJS endpoint in Spring MVC?
- How to load classes from jar file in-memory stream
- How to call a method on an object in a nested form in Ruby on Rails 3?
- How to disable field validation on MVC view?
- How to load page synchronously using jQuery
- How to remove lines based on another file?
- How to combine rows based on unique values in R?
- Copy Row To Another Sheet Based On Cell Value In Google Sheet
- How to load .mat file which has a variable filename?
- Ruby on Rails: How to redirect page based on post params in search_field?
- How to star a post on a facebook fanpage using graph api?
- How to work with navigation properties (/foreign keys) in ASP.NET MVC 3 and EF 4.1 code first
- JOOQ How to convert JSON based on other column value?
- How to group arrays based on another array in mongodb aggregation?
- How to change images based on keystrokes
- How to copy file based on matching file name using PowerShell?
- How to make user return on login page after sign-up in Azure AD B2C?
- How to Fetch records based on the Dates in MYSQL
- How to convert UTC time to local timezones based on timezone column in bigquery?
- How to select rows based on conditions for each id
- How do I make link_to open external URLs in a new window?
- ASP.NET MVC 4, Migrations - How to run 'update-database' on a production server
- How to implement Role based restrictions/permissions in react redux app?
- D3 How to change dataset based on drop down box selection
- How to configure services based on request in ASP.NET Core
- How to load a script on $(document).ready()/onDeviceReady() of jquery-mobile/phonegap
- How to install packages based on the lock-file with Yarn?
- How to set class based on current route name/controller
- How can I make my class pretty printable in Python?
- Standalone ruby — How to load different environments from database.yml
- How to load views from a Class Library project?
- How to return correct response on error in ASP.NET MVC 3.0 via JSON?
- How to show the model's attribute dynamically in mvc?
- ruby: how to load .rb file in the local context
- How to ORDER BY based on two different columns
- how to sort dataframe based on particular (string)columns using python pandas?
- How to load cross domain html using jQuery
- How to sum rows based on multiple conditions - R?
- How to categorize data based on column values in pandas?
- Entity Framework 4.1 - Code First with existing Database, how to define classes, using Attributes or...
- Android: How to load image into Bitmap
- How to use Session Affinity on requests to Kubernetes service?
- How can I to load and query local json data in Flutter Mobile App
- How to pass variables with spaces through URL in :Django
- Castle Windsor - how to resolve components based on constructor parameters
- Load balancing based on proximity
- How to get users based on role?
- How to load a Model into _Layout.cshtml and share it among various Views?
- How to properly redirect (while setting a cookie) in MVC3/Razor?
- Is it possible to reuse partial views on multiple projects in ASP.NET MVC?
- How to filter array based on nested value in Javascript
- Python - how to load Google Chrome or Chromium browser in the gtk.Window like webkit.WebView()?
- How to block requests based on post data?
- How to pass textbox value into query string in asp.net mvc
- How to test Intent based on Espresso in Android?
- How to sort values based on selection in an Altair chart?
- How to display values from Navigation Property collections in MVC Index page
- Using Event Aggregator to load a view with different model in backbone js
- How to turn Razor Model into JS object in a Razor For Loop?
- how to make friends based on follow/follower , Swift Firebase
- How to subset data based on predefined pattern in R?
- Jenkins Multibranch Config: How to Filter branches based on variable string?
- How to override RTL support on a layout in Android
- How to prevent Google Chrome from saving passwords in ASP.NET MVC?
- How to disable content based on checkbox in AngularJS/Bootstrap3
- How to get base url of the site in MVC
- How to get PDF content (served from a Spring MVC controller method) to appear in a new window
- How to load JSON Data on google visualization Chart?
- Where should a script block with jquery code be placed on an ASP.NET MVC Master Page?
- Where to put scripts in MVC _layout page
- How do I hide an element in the shared layout based on the controller in MVC
- Dart - How to format DateTime based on device timezone?
- Bixby : how to get informations based on my location? such as weather etc
- how to update table based on another table in mysql?
- How to render ModelMetadata object using Html.Displar in Razor-engine in ASP.NET MVC app?
- How to load native library on android?
- Adding an error message to the view model based on controller attribute in ASP.NET MVC
- How to Load Partial Views with Jquery UI Tab by passing parameters?
- How to filter geodjango based on longitude and latitude
- How to deal with jQuery bootgrid request data in MVC
- How to set the welcome-file when developing spring mvc application with pure Java based configuration and no web.xml?
- How to load data into datatable using ajax in mvc
- How to count characters based on its font?
- How to do mapping for LIST of object in spring mvc framework
- How to load data asynchronously using AngularJS with SpringMVC?
- Spring MVC 2.5: how to load properties file
- How to update database model on a deployed asp mvc web site without losing data
- How to group values based on NA vs. alphabet
- How to create a simple bootstrap modal dialog in ASP.NET MVC
- How to show content based on url parameter via JavaScript?
- How to Delete Rows Based on Criteria from 2 Columns in VBA?
- How to Debug the White Screen of Death in ASP.NET MVC
- How to get a specific row from database in MVC 4
- Parsing to primitive types, based on user input in c#
- How to change bordercolor based on value of textbox? using javascript
- How to load html views in spring?
- Append values to one dataframe based on their frequency in another dataframe
- Dynamically change form based on value selected in combobox in Ruby on Rails
- How to call and refresh a partial view in MVC 5 razor?
- How to filter children based on whether the parent is filtered in D3?
- How to junit return type of a method in spring mvc controller
- How to show divs based on drop down selection when validation fails
- How to add a checkbox for each row in Rails 3.2 index page?
- How to Insert Records based on the Previous Insert?
- How to retain data (form) on custom pagination using MVC?
- How to autocomplete forms based on the name entered
- How to load images from a specific group?
- Google Picker API - how to load a picker on demand
- C#: How to set default value for a property in a partial class?
- How to return error message from FileResult method in asp.net MVC 4 application?
- How to Show and Hide Div using C# in MVC 3 Razor View Engine?
- How I can check debug mode in MVC cshtml page
- Do I have to Load/Get an entity before SaveOrUpdate in Nhibernate?
- Is it possible to disable authentication Filter on one action in an MVC 5 controller?
- How to select parent based on the child in lxml?
- How to highlight rows based on content in Excel Dataframe?
- How to reference outer object from inner class in Scala
- How to re-use SqlCommand object for a CommandText after executing a query based on stored procedure in C#?
- how to pass data from View to Controller using ajax get or post in mvc with parameters
- How to load a text file in JavaScript?
- How to filter rows based on the sequence-related constraint?
- How to find element based on what its value ends with in Selenium?
- How to create conditions based on user role using JSF/MyFaces?
- How to rotate log based on an interval unless log exceeds a certain size?
- How to color rows based on cell value in OpenOffice and LibreOffice
- How to list files based on matching only part of their filename?
- How to load startup programs on different Task Views?
Only authorized users can answer the search term. Please sign in first, or register a free account.
The autoloading and routing are separate things.
From the look of you posted code, it's obvious, that you have a single class, which is responsible the following tasks:
In OOP there is this thing, called: Single Responsibility Principle [short version]. Basically it means that a class should be handling one specific are thing. The list above constitutes at least 4 different responsibilities for your
Autoload
class.Instead of what you have now, each of these general tasks should be handled by a separate class. And in case of autoloader, you could get away with a single function.
How to do write your own autoloading code ?
Part of the problem that I see is the confusion about how autoload actually works in PHP. The call of
include
orrequire
doesn't need to be done where the instance will be created. Instead you register a handler (usingspl_autoload_register()
function), which then is **automatically* called, when you try to use previously-undefined class.The simplest example for it is:
This particular example uses anonymous function, which is one of features that was introduced in PHP 5.3, but the manual page for the
spl_autoload_register()
will also show you examples how to achieve the same with objects or ordinary functions.Another new feature that is closely related to autoloading is namespaces. In this context the namespaces would give you two immediate benefits: ability to have multiple classes with same name and options to load class file from multiple directories.
For example, you can have code like this:
.. in this case you can have autoloader fetching classes from
/project/controllers/overview.php
and/project/views/overview.php
files respectively. Because thespl_autoload_register()
will pass"ControllersOverview"
and"ViewsOverview"
to the handler function.There is also a FIG recommendation for how to implement autoloaders. You can find it here. While it has some significant problems, it should provide you with good base on which to build upon.
How to parse pretty URLs ?
It is no secret, that Apache's mod_rewrite is quite limited in what it can do with pretty URLs. And, while it's a widespread server, it is not the only option for webservers. This is why for maximum flexibility PHP developers opt to handle URLs on the PHP end.
And the first thing any newbie will do is
explode('/', ... )
. It is a natural choice, but you will soon notice that it is also extremely limited in what it can really do. The routing mechanism will start to grow. At first based on count of segments, later - adding different conditional values in segments, that require different behavior.Essentially, this will turn in huge, fragile and uncontrollable mess. Bad idea.
Instead what you should do is have a list of regular expressions, that you match against given pretty URL. For example:
The above defined pattern would match all the URL that have two segments, with some text in first segment and
"foobar"
in the second ... like"/testme/foobar"
.Additionally you can link each pattern with corresponding default values for each match. When you put this all together, you might end up with configuration like this (uses 5.4+ array syntax, because that's how I like to write .. deal with it):
Which you could handle using following code:
Live code: here or here
You probably will want to generate the regular expressions for the matching from some more-readable notations. For example, in configuration file, this expression:
.. should probably look something like
Where the
:param
would indication an URL segment and[...]
would signify an optional part of URL.Based on this you should be able to flesh out your own routing system. The code fragments above is just example of simplified core functionality. To get some perspective on how it might look when fully implemented, you could look at code in this answer. It should give you some ideas for your own API version.
Calling the stuff on controllers ..
It is quite common mistake to bury the execution of controllers somewhere deep in the routing class (or classes).This causes two problems:
Routing is a task which even in custom-written application will naturally gravitate toward the "framework-ish" part of codebase.
The (really) simplified versions would look like:
This way there is nothing that requires your routing results to be used in some MVC-like architecture. Maybe you just need a glorified fetching mechanism for serving static HTML files.
What about those dynamically extend categories?
You are looking at it the wrong way. There is no need for dynamically adding methods to controller. In your example there is actually one controller method ... something along the lines of:
Where
$category
would end up containing"cosplay"
,"game"
,"movie"
,"series"
or any other category that you have added. It is something that your controller would pass to the model layer, to filter out articles.What people actually use professionally?
These days, since everyone (well .. everyone with some clue) uses composer, for autoloading the best option is to use the loader that is comes bundled with composer.
You simply add
require __DIR__ . '/vendor/autoload.php'
and with some configuration it will just work.As for routing, there are two major "standalone" solutions: FastRoute or Symfony's Routing Component. These ones can be included in you project without additional headaches.
But since some of people will be using frameworks, each of those will also contain capability of routing the requests.
Some further reading ..
If you want to learn more about MVC architectural pattern, I would strongly recommend for you to go though all the materials listed in this post. Think of it as mandatory reading/watching list. You also might find somewhat beneficial these old posts of mine on the MVC related subjects: here, here and here