开发者

PHP: Is there an path specification convention?

One problem I see all over the place is the big question: "must I put an / in front of a path, or must I not?"

Sorry if this appears subjective, but for 开发者_StackOverflowmy framework it's an important question: Do you think that it's more logical to put a "/" in front of every path when specifying one, or do you think the "/" prefix should be avoided?

Or should I check if the first char is "/" and if not, add that automatically?

Context: Framework functions that take paths.


If you put a / in front of every path, then those paths are absolute. Without it, they are relative. Not sure what you're after, but that's what the / at the beginning is for.

For example, if your current directory is /var/www/html/ and you give your path as foo/bar/, the path becomes /var/www/html/foo/bar/.

If you give your path as /foo/bar/, then the path is just that, with nothing prepended.

So the forward slash is just a matter of where you're looking the files from, and if you're using the paths as a argument to a function, you probably want to pass them as relative (to the framework directory).


The best convention is whether or not you intend the path to be relative or absolute. Generally, a leading '/' specifies an absolute path, from the root of a file system, or the root of a website.

Take an example CSS file, located at at mysite.com/files/css/info.css

...
background-image:url('/bg.png'); /* absolute - use mysite.com/bg.png */
background-image:url('bg.png');  /* relative to info.css - use mysite.com/files/css/bg.png */
...

In your own code, when you have an option of ommitting or including a leading slash, you can follow a similar convention:

<?php

// $uri - the relative/absolute uri to link to, ie /posts or 'show/id'
// $text - the text link
function link_to($uri, $text) {

  if ($uri[0] == '/') {
    // assume absolute
    $href = $uri;
  } else {
    // assume relative to current uri; remove last segment and replace
    $uri_segments = get_uri_segments();
    array_pop($uri_segments);
    array_push($uri_segments, $uri);
    $href = implode('/', $uri_segments);
  }

  return "<a href=\"$href\">$text</a>";
}

//
// elsewhere, assuming current URL is 'myself.com/users'
//

// relative link to 'create'
link_to("create", "Show User"); // mysite.com/users/create

// absolute link to '/products'
link_to("/products", "Products"); // mysite.com/products

?>


I like to have it because it makes it easier to add on files and it avoids confusion to always have it. For example:

http://example.com/ + file.php IS http://example.com/file.php = path
http://example.com + file.php IS http://example.comfile.php = error
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜