Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BaseController uses for what in MVC?

I look more tutorial about MVC. But I didn't understand, people are using "BaseController" for what? In one project someone use it forcommunication between all controller. In other project someone use for get logs. Can you explain to me completely?

like image 282
mert Avatar asked Feb 01 '26 16:02

mert


1 Answers

It is a very common practice for some developers to create a "BaseController" or really, a BaseAnything class to use for common functionality, and then derive other things from that BaseWhatever in order to reuse that functionality. This is just basic Object Oriented Programming techniques, and have nothing specific to do with MVC (other than the fact we're talking specifically about a BaseController in this instance).

There are some, and I happen to be among them, who believe that explicit Base classes are often a code smell, and are often severely abused as "catch alls". All too often, people put all kinds of stuff in these base classes for convenience, because it's easier than creating some other mechanism to share code or data in a better way.

I avoid Base classes unless absolutely necessary. I tend to prefer other methods to achieve the functionality that is often achieved this way (I call it lazy reuse). Examples of alternatives are:

  • Extension Methods
  • Html.Action methods
  • Attribute Frameworks, such as AOP
  • Dependency Injection
  • and many more..

You may create a base class with the best of intentions, and claim it will only be used for a very limited function... but before you know it, others that are developing in your project are stuffing all kinds of stuff in there.

My rules is, Just don't do it. Avoid creating a base class at all costs, unless there really is no other good way to do it.

*NOTE: I'm referring to concrete base classes used for the sole purpose of sharing implementation/data. Generic and abstract base classes are a bit of a different story, as are base classes used for Taxonomy (ie is-a relationships) and hierarchical purposes. In general, if you have called something FooBase or BaseFoo, it's probably of this type.

There are also other exceptions to this rule, such as when wrapping an untestable class for testing purposes, you often create a base class for this purpose, or in frameworks you sometimes deliberately build a base class that is intended to be inherited, but isn't generic or abstract. It's there to provide functionality to fit within the framework. But, these are not things you often have control over when using those frameworks.

like image 83
Erik Funkenbusch Avatar answered Feb 04 '26 06:02

Erik Funkenbusch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!