max max - 4 months ago 15
PHP Question

Is it bad practice to use the same method for SAVE and UPDATE?

so im using laravel but it's not important , when you create a controller with laravel command line tool , it puts 4 default function in there for create and update ...

create
and
store
for
save


edit
and
update
for well
update
!

this is what laravel suggest for Shop controller

class ShopController extends Controller
{

public function create()
{
// return create view
}

public function store(Request $request)
{
// save a shop
}


public function edit($id)
{
// find a shop , return edit view
}

public function update(Request $request, $id)
{
// find the shop with id , update the shop
}

}


but i like to use the same methods for showing view and store/update my row and avoid writing lots of extra code

class ShopController extends Controller
{

public function create($id = 0)
{
return view('shop-create' , ['edit'=> Shop::find($id)]);
}

public function store(Request $request , $id = 0 )
{
$whitelist = [
'title'=>'required',
'phone'=>'present|numeric' ,
'address'=>'present' ,
];
$this->validate($request, $whitelist );
$shop = Shop::findOrNew($id) ;
// find a shop with given id or create a new shop instance
foreach($whitelist as $k=>$v)
$shop->$k = $request[$k];

$shop->save();
}

}


naturally i go with what i like (second option) , but since laravel suggest the first way , just out of curiosity is there any reason why i shouldn't do it like this ? is this considered bad practice in any way ?

Answer

Nothing wrong, but you code will be harder to understand, IMHO.

e.g.:

  • What do this method do? It's called create, but it also edit?
  • The view is called shop-create but it also edits?
  • Passing a 0 parameter as default for id and try to find it every time is unnecessary.

public function create($id  = 0)
{
    return view('shop-create' , ['edit'=> Shop::find($id)]);
}

Although you're thinking that you are simplifying your code, you are turning it more complicated since you are broking the Single Responsability principile from SOLID.

It's easiest to understand if you have something like the Laravel suggestion.

Also you keep a very common pattern that any Laravel developer will understand, so you can hire someone to take care of your code and do not worry if he will understand.