PHP OOP routing - php

i want to make a very simple website but with OOP PHP. I got enough experience in programming (c#, c++, php, js and more) so i know how to make classes etc, but the thing i dont understand with php is the correct way to call things.
there are hundreds of tutorials oop php on the internet but nothing with this (or maybe its a weird question :P).
let me explain.
for example i want a news website and i got a class News with the function create.
if i follow the url mywebsite.com/news/create or mywebsite.com/news?action=create i want to execute the php class News, action create.
but how am i suppose to do this. do i need to make in index.php
if(action == news) news->create();
and for every action another... i dont think so :P. so how can i make this correctly? or is it better to take a simple mvc framework?
Thnx,
Stefan.

I would use the CodeIgniter framework for this, it is EXTREMELY easy to install, plus it uses the the MVC design pattern.
Then to make your url like this: "mywebsite.com/news/create" you can change a simple thing in the htaccess file like such:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
Source:
http://codeigniter.com/user_guide/general/urls.html
If on the other hand you don't want to use a framework, you can just use Apache's mod_rewrite to remove the script filename, then using php's explode function to get the function and parameters from the $_SERVER["REQUEST_URI"] variable.
There is a good example here:
http://www.phpaddiction.com/tags/axial/url-routing-with-php-part-one/

i know many frameworks and i worked with codeigniter, and yii. I prefer yii but the mean question for me is, is it possible to work without such frameworks and route things or is it better to take a framework.

Related

Rewriting url to hide index.php and to make query nice

I had developed project with custom MVC architecture. And I am new to Apache world, so I would appreciate help with this matter. On a Web I had found lots of tutorials, but no one like mine interests.
I have URL like this: http://knjiskicrv.comoj.com/index.php?page=book&id=1
I would like to be display like this: http://knjiskicrv.comoj.com/book/id/1
Or this: http://knjiskicrv.comoj.com/index.php?page=faq
Into this: http://knjiskicrv.comoj.com/faq
If there is no page in query (http://knjiskicrv.comoj.com/index.php), I would like to show: http://knjiskicrv.comoj.com/
Also with no page in query (http://knjiskicrv.comoj.com/index.php?category=2), it should be like this http://knjiskicrv.comoj.com/category/2
Hope someone will help. Thanks.
Actually, your problem is a two step proble. You first need to understand what is "Routing" in MVC. If you have your own implementation of an MVC like framework and you don't support routing, then it probably means you didn't even know how it worked before. (Sad but true)
In an MVC framework you setup routes using a ROUTER and the router analyses the urls for you saying HEY, i found this url that matches your request, go ahead and do work with it.
So then, your controller receives a request to route into itself and PARSES the url as he sees fit. Such as using explode('/', $_SERVER['REQUEST_URI']) and then reading the different parts of the url to map to expected variables.
All of this is very theoretical because there are ZILLIONS of way to implement it in a custom way. The only thing you will have to use is a little mod_rewrite magic to pass all requests to your index.php that will route everything. Look at the url below to learn about mod_rewrite, it's a VERY COMPLEX subject:
http://www.addedbytes.com/for-beginners/url-rewriting-for-beginners/
What i usually go for but i don't have access to it from home is something like this:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^assets/
RewriteRule .* index.php
This will redirect all traffic to index.php and you can then use $_SERVER['REQUEST_URI'] to analyze the request. Everything in assets/ folder will not be touched and work correctly.
Note, i built that part off my hat, it might not work...

How should I manage a PHP database-driven website with lots of pages/content?

Let it be known that I only have experience making websites with 5 or 6 pages. I'd like to make a PHP Gaming journalism site like http://www.escapistmagazine.com/
The first problem I can think of is that I would have to manually make a page for each game article; that path was obviously not going to work so I decided to store all the articles in a database.
The problem with storing the content in a database was figuring out how to retrieve them. I attached a GET variable to the url so I could retrieve any article from an index.php file; however, I could not hide the GET variable from the url so I ditched that method. I have no free cash to buy a CMS and I have tried free ones like Drupal to great frustration.
Do I have to generate a separate php file for each article? What would a professional/veteran do in my situation?
First, I'd like to state that if you are having trouble finding the patience to set up Drupal, Wordpress or similar free CMS', you would be hard pressed to find the patience to creating one from scratch.
Having said that, to address the specific request you're looking for, I believe you want to use mod_rewrite to funnel your requests through a single file, which would, in turn, hand the request off to the appropriate file. Drupal, for instance, uses the following rules:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
Which routes your URL into a single variable, 'q'.
I manage a CMS that publishes PHP pages statically like you're considering. Coming from MVC designs, it is horrific, and I highly suggest you not take that route.
I'd check into one of the frameworks like Code Igniter, Cake, or if you feel like you want to torture yourself, Zend. All joking aside, you'll be able to create routes that use the URL request to find the content that you're looking for. I won't go into the whole concept of MVC and routing here, as it is well documented throughout the web, but essentially it keeps template management much easier. As a matter of fact, pretty much everything is easier, and your codebase stays much cleaner.
Right now, I've got a codebase for my CMS of almost 400mb. This is because there's an abundance of static pages that are indexed. This would be cut significantly to ~50mb (if that) if I converted it to an MVC framework. Keep in mind, this is without user generated content like PDF, MP3, etc.
If that seems scary, I highly suggest using Joomla!, Drupal, Wordpress, or any of the other CMS systems out there. Trust me, you'll save a ton of time.
The best advice I could give you: use Wordpress, don't rebuild it yourself. It's really perfect for this job.
Bottom line: 15% of the best websites run using Wordpress.
When you start considering security, maintainability, time, and other factors - for what you are describing I would just use WordPress. Free, easy to setup and proven. It's not just making the frontend site for your viewers, you also need all the admin tools to manage it all as well.
If you do build your own, you will want to use a database to store your data. You won't create a php file for each article, you will most likely have one or few php files that focus only on loading an article page from the database using rewrite rules for nice urls. Good luck with the path you choose.

Rewriting a CI url

I have never before rewritten a URL except for removing the index.php part of my CodeIgniter installs, and that I do by using a copy-pasted snippet in my .htaccess file. I haven't had the time to actually learn about what the snippet does; I'm basically very new to rewriting URLs.
I have a mobile version of my web application. I got as far as redirecting mobile users to a subdomain: m.myhost.tld. However, since I'm using (one) CodeIgniter (install), I have to send these mobile users to a mobile-specific controller, in my case /mobile/. So, the controller always shows up in my address bar.
I just don't think this is very clean, and I'm looking for a way to rewrite the URL; but truth be told, I'm not even sure if this is possible.. hence my question.
I want to get rid of the /mobile controller part. Is this possible?
Some examples:
My current mobile 'root' folder is
http://m.myhost.tld/mobile
I would like to turn this one into
http://m.myhost.tld/
At the moment, when I go to http://m.myhost.tld/, it redirects to the default controller for my CodeIgniter application, which is part of the 'desktop' version of the web app.
Another example:
Turning
http://m.myhost.tld/mobile#mobile/about
into
http://m.myhost.tld/#mobile/about
I'm not sure if I'm making any sense here. I am in my head, but like I said, I don't know what exactly is possible. If the user is on the m subdomain, I want to hide the /mobile part of my URLs. However, only when we're on the m subdomain, so the 'desktop' version (which sits at www ) does not get touched at all.
Like I said a couple of times now, I'm not sure what is possible and what I'm looking for might just be too complex or whatnot. I figured I would ask though, since learning by asking is what I do best. Please don't be too hard on me if this turns out to be a dumb question, sirs professionals ;)
EDIT:
I thought I'd edit because I don't want to come off wrong. I'm not necessarily looking for exact answers to my question. I also welcome documentation/tutorials/articles that might guide me to a solution. If I can manage to come up with a solution of my own, I will of course learn a lot more.
Thanks a lot.
This could be too simple of a solution but why not in your routing config do something simple like
in your config do something like
if ($_SERVER['SERVER_NAME'] == 'm.myhost.tld')
$route['default_controller'] = "mobile";
This would make the default controller mobil so you wouldn't have to have /mobile...
As i said maybe too simple
EDIT: Doesn't work, but maybe someone can turn it into something that does
Try this:
RewriteCond $1!^mobile/
RewriteCond %{HTTP_HOST} ^m\.myhost\.tld
RewriteRule (.*) /mobile/$1 [L]

A RESTful persistence solution usable with backbone.js... in PHP?

I'll preface this with saying that I'm a crappy programmer, I'm sure that what I want to do could be done in 10 lines of node or Rails or something else, but PHP is what I have available.
So, I'm hoping to find a simple PHP library which wraps the database calls in an API that looks similar to the RESTful model.
I've had little success trying to find such a thing -- searching for PHP CRUD or PHP REST turns up several zillion pages, and I've no idea how to filter through them.
I'm really trying to keep things simple here, I don't want a big framework like Zend or something. The models I'm dealing with in Backbone are really simple. I just want to send GETs to, say, /notes/3 or POSTs to /notes, etc, and have PHP do the right thing to a database.
Perhaps I'm asking too much, but it seems to me that this is what other frameworks like Rails provide. Any suggestions? TIA...
EDIT Nov 2018: Although I wouldn't knock CodeIgniter, nowadays Laravel (currently 5.5) is the framework I use.
Here is a good article that sums up the reasons I use Laravel.
To get jump started, I recommend Laracasts. It's a subscription video tutorial service that goes in depth on how to use Laravel (and other web dev related things).
ORIGINAL ANSWER:
Codeigniter, to me, is the easiest of the Rails-like frameworks. It's bare bones, and you can build a CRUD app from scratch easily.
The biggest issue with rolling your own app is security. Codeigniter can help you build a less hackable site by shielding you from many of the common security risks, such as using $_POST arrays directly, and not properly filtering your data. Not to mention the many helper classes it offers such as form validation.
You can view the documentation on their website. It's very easy to use as long as you remember the navigation is hidden at the top of each page. :D
Do you understand how CRUD works internally? From a PHP standpoint, it could be as easy as having a switch statement over each REST call possibility.
See this page here:
http://www.codethinked.com/building-epic-win-with-backbone-js
Skip to the section titled "Wiring It Up To The Server".
Your PHP script simply has to satisfy those requirements.
A simple prototype code:
switch($_SERVER['REQUEST_METHOD']){
case 'POST':
// create new item
break;
case 'GET':
// get item(s)
break;
case 'PUT':
// update item
break;
case 'DELETE':
// delete item
break;
}
You will also need to set up a .htaccess file as follows (to handle accessing non-existent urls):
# Turn on rewrite engine and redirect broken requests to index
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L,QSA]
</IfModule>
A URL like http://mysite.com/1 doesn't real exist, which is why you need to route.
Edit: In case you are planning to use PUT or DELETE in HTML forms, forget it. As of writing this, it has not been accepted in HTML5, and pretty much all browsers fail to support this. My "fix" to this is to use GET for GET requests, and POST for all the rest (POST itself, PUT and DELETE). Example:
<form action="POST" action="/users/5">
<input type="hidden" name="method" value="DELETE"/>
<button>Delete User #5</button>
</form>
This, however, is not a problem with AJAX since apparently you can set XMLHttpRequest Method to anything you want without problems.
There are lots of restfull frameworks for PHP, have a look here and here.
I personally like fat-free-framework but you need PHP 5.3 for it.
Also there is a lot of support for Tonic and Recess seems quite interesting.
Also all the standard frameworks have some sort of rest support (zend, code igniter, symfony and the likes)
You should find your fit ..
Also if you already have your mysql queries ready, you could convert the mysql results directly into json like this :
function recordSetToJson($mysql_result) {
$rs = array();
while($rs[] = mysql_fetch_assoc($mysql_result)) {
// you donĀ“t really need to do anything here.
}
return json_encode($rs);
}
After that it's quite easy to associate with urls ..
From : Convert MySQL record set to JSON string in PHP
You can use silex https://github.com/fabpot/Silex a simple framework based on symphony 2. With Silex you can easily route and map action.
You have access to the basic CRUD element and you can call a function with the URL component.
There are some examples on the documentation :
http://silex-project.org/doc/usage.html
new REST api solution
examples
http://www.apifysnippets.com/
code
https://github.com/apify
tutorial
http://blog.fedecarg.com/2011/09/11/building-a-restful-web-api-with-php-and-apify/
UPDATE:
another rest solution for PHP:
http://luracast.com/products/restler/
:)
you might want to look at Slim:
http://www.slimframework.com/
its definitely light-weight and can give you what it seems like you're looking for, an easily deployed RESTful backend with php.

Creating a RESTful API and website with PHP

I've got a PHP application I wrote earlier that I'd like to add a RESTful API to. I'd also like to expand the site to behave more like a Rails application in terms of the URLs you call to get the items in the system.
Is there any way to call items in PHP in a Railsy way without creating all kinds of folders and index pages? How can I call information in PHP without using a GET query tag?
If you have some form of mod_rewrite going you can do this quite easily with a .htaccess file.
If you have something like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
It will check that the file you are trying to access doesn't exist already. (Say you had a file hello.html that you still needed people to access via http://yoursite.com/hello.html)
Then if the file doesn't already exist it will load your index.php file with the rest of the URL stored in the url variable.
This means you can call something like this http://yoursite.com/pages/edit/24 and it will load index.php with /pages/edit/24 inside the url variable.
That should get you started and you won't need all kinds of folders and index pages, just mod_rewrite, .htaccess file and an index.php that will be used to load whatever you need.
You also might consider to use one of the PHP frameworks with built-in REST support, for example CakePHP.
Quick note in respopnse to Pascal MARTIN: Zend_Rest_Server has absolutely nothing to do with REST. They just do RPC with slightly nicer URLs and call it REST so that it's more trendy.
If you want to do REST, you'll need to do a bit more work yourself as I have not found a good REST library for PHP yet. So inspect $_SERVER['REQUEST_METHOD'] to decide what to do with the called resource, etcetera.
Easiest way would probably using a framework that provides you with REST-oriented functionnalities. I know Zend Framework does that, with the class Zend_Rest_Server, that allows easy creation of a REST server.
I suppose many other frameworks do just the same.
But, if you already have an application that doesn't use a framework (or that is based on a Framework that doesn't embed that kind of class), a couple of URLrEwriting rules would do just fine ; you'd just have a bit more work to map URLS/parameters to classes/methods :-(
The design pattern you are looking for is called a front controller.
In its simplest form you use mod_rewrite to pass the incoming requests and pass it to a single php script. The url is then parsed with regular expressions and mapped to different response actions. However mapping an existing application may require extensive rewriting.
If you want to play around with this concept I recommend the Silex microframework.

Categories