Search code examples
phplaravelshared-librarieslaravel-3

How can I reuse some laravel code?


I am developing web application using the laravel. I would like to 'package' some of the functions, which is re-usable. For example, I got a UserController, with database setup, and view, etc. The UserController is expected to re-use in most of the web development in the future, but some UserController may have different behavior, for example, some application's user may have a field rewardPoint, some may not. But they all have some similar behaviors, for example: register, login, forgetPassword, etc. So, can I package out a common UserController with all the basic database setup into one file or script to reduce the development work load? Thanks.


Solution

  • You've hit the nail on the head already - since your requirements are likely to change between projects you will struggle to create a single solution that works everywhere. You have a few options, including:

    1. Copy the useful classes from your last project and update them to fit.
    2. Create a package or bundle of base classes that include common and reusable code, then extend these into your project and modify the extensions as needed.
    3. Attempt to create a "one solution for all" that you can drop in to all of your projects.

    I would steer away from 3; it's likely to add the most bloat for the least gain. 1 is useful whilst you get used to the framework, especially if you tend not to revisit old projects; over time you will refine your code and develop patterns of work. Eventually you will probably end up doing 2; you can store these in git, use bundles or composer packages, and you can continue to improve them over time.