简体   繁体   中英

How do I specify a URL pattern for a function in PHP?

I am trying to use PHP , REST and Angular .

I have a userAPI.php file which has several functions like: getUser($uid) , etc.

I hava a DAO method which return the userObject from the database of the specified userID .

Now, in Java when we use JAX-RS we can specify URL pattern with annotation which looks something like:

@url('user/{uid}')'
@get
public void getUser(Integer uid){
   //func body
}

But I am not sure how to do that in PHP.

Then I googled and got to know about .htaccess .

I tried:

RewriteRule user/(.*)$ php/service/userAPI.php?uid=$1 [QSA,NC,L]

But I am not sure if it's correct.

What should I write inside .htaccess and $http.get() ?

A PHP script does not call any functions automatically. To test whether your rewrite rule is taking effect do the following:

userAPI.php

<?php
require_once "userMethods.php"

$uId = (isset($_GET["uid"]))?$_GET["uid"]:null);
if ($uId === null) {
    echo "No user id provided";
}
$user = getUser($id);

userMethods.php

<?php
function getUser($id) {
     //Get the user 
}
// Other functions?

While it is possible to declare all functions in the userAPI.php file before any of the code which will run, it's probably better practice to separate function declarations (and class declarations) from runnable scripts.

I do however suggest you use a proper PHP MVC framework. Laravel is a pretty good one, though it does have a learning curve so if you just need to do some simple things in PHP and then never code in it again it probably isn't worth the time investment.

You Should really look at this. This will handle all of the routing for you and is pretty easy to set up. Once the routes are defined you can call your own functions.

http://www.slimframework.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM