问题
I added a cart package to my Laravel install, but I need to add a method to the class. If I modify the class directly, will my changes be overwritten when I update to a newer version? If so, what's the best method for modifying a package without breaking future updates?
Thanks for the help! -JB
回答1:
I don't know if there is any general process to extend Laravel 5.0 package from vendor directory and I am sure this may be different for different packages. But saying that, I faced the same issue when I wanted to extend this cart . But I managed it somehow and steps I followed are below. I hope it may give some hint.
Install the package
composer require "gloudemans/shoppingcart":"~1.3"
Create directory
app/Services/Cart
and a new classMyCart
under it<?php namespace App\Services\Cart; use Gloudemans\Shoppingcart\Cart; class MyCart extends Cart { }
create
CartServiceProvider
underapp/Providers
directory,<?php namespace App\Providers; use App\Services\Cart\MyCart; use Illuminate\Support\ServiceProvider; class CartServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app['mycart'] = $this->app->share(function($app) { $session = $app['session']; $events = $app['events']; return new MyCart($session, $events); }); }
}
Create
MyCartFacade
underapp/Services/Cart
directory,<?php namespace App\Services\Cart; use Illuminate\Support\Facades\Facade; class MyCartFacade extends Facade { protected static function getFacadeAccessor() { return 'mycart'; } }
in
config/app.php
add following inproviders
array'App\Providers\CartServiceProvider'
and following in
aliases
array'MyCart' => 'App\Services\Cart\MyCartFacade'
That's it. Now in my controller I placed following code.
add
andcontent
are method in baseCart
class.\MyCart::add('293ad', 'Product 1', 1, 9.99, array('size' => 'large')); echo '<pre>'; print_r(\MyCart::content()); exit();
and following is the output,
Gloudemans\Shoppingcart\CartCollection Object ( [items:protected] => Array ( [0f6524cc3c576d484150599b3682251c] => Gloudemans\Shoppingcart\CartRowCollection Object ( [associatedModel:protected] => [associatedModelNamespace:protected] => [items:protected] => Array ( [rowid] => 0f6524cc3c576d484150599b3682251c [id] => 293ad [name] => Product 1 [qty] => 1 [price] => 9.99 [options] => Gloudemans\Shoppingcart\CartRowOptionsCollection Object ( [items:protected] => Array ( [size] => large ) ) [subtotal] => 9.99 ) ) ) )
Now if you want to add or override functionality simply put that function in MyCart
class.
The good thing is, you can update the base package.
I hope it helps.
来源:https://stackoverflow.com/questions/28076332/laravel-extend-package-class