简体   繁体   中英

Creating Shared libraries in PHP

Im working on a few php based projects and im having an issue of having to maintain separate code bases with common code . The common code shared amongst all the projects is added physically (file are copied in the folder) and when a change is needed we have to manually replicate the fixes in the common code functionality in each project.

In java we can create a library (jar file) and share it among different projects. Is there any shared library related concept available in PHP 5.

PHP的jar版本称为Phar: http//php.net/manual/zh/book.phar.php

Wouldn't it be easier to check the shared code into a version control repository, and check it out into the projects? For example, SVN supports that with the svn:externals property

Although PHP now supports phar files, the right way to solve the problem is by using include files (and paths) effectively.

The include path is always searched in the same order for files - so a good practice is to to have 2 hierarchies defined, one for the scope of the code (eg everything, application, module) and one for the environment where it is running (holding such things as related URLs, batabase connections etc eg everything, environment (development / test / live), cluster node)

C.

I've also been pondering the same problem. Here are some thoughts.

Approaches

1: Set the include path to one shared folder from all your projects. It shouldn't break anything if you're careful about backward compatibility while writing/modifying your library. But yes it's very risky because if you do break something, it will be broken on all your projects.

2: Create a simple update script included with your library that copies the files from the main source to your project. Run this script when you update the library.

3: Use a version control setup. Git submodules might work ( http://book.git-scm.com/5_submodules.html )

4: Phar files are something I'd like to try. It's only drawback is that they don't work with PHP versions lower than 5.3

UPDATE: 04/12/2011 - I recommend using approach #3. Now that I've used it for a while, it seems to be clearly the best practice.

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