MVC, Business Logic, and other things that hurt my brain

  • (2 Pages)
  • +
  • 1
  • 2

23 Replies - 21516 Views - Last Post: 30 May 2012 - 06:45 AM Rate Topic: -----

#1 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 800
  • View blog
  • Posts: 1,688
  • Joined: 30-January 09

MVC, Business Logic, and other things that hurt my brain

Posted 02 September 2011 - 08:29 PM

After studying MVC for months and months, I'm finally getting somewhere solid. I still feel like there is some shaky ground though, and the concept of business logic, what exactly it entails, and where it should reside still causes me some trouble. Take this real world example:

I have a database with a table named 'Items', that have a few simple attributes. Let's assume it looks like so:
ID  Name      IsEdible
--  ----      --------
1   Apple     1
2   Chair     0
3   Bread     1



Let us also assume that we want to print this data out to the screen like so:
Item   Is this edible?
----   ---------------
Apple  Yes
Chair  No
Bread  Yes



Now, the MVC pattern basically says that this should happen:
  • The controller is instantiated
  • The controller asks the model for the data
  • The controller reads in the template (the view)
  • The controller replaces the placeholders in the template with the data it got from the model
  • The controller sends (serves) this result to the end user


All pretty simple. My question is this: At some stage, the column IsEdible has to be converted from bit value (1/0) to a string value (Yes/No). Should the model be doing this, or should the controller be doing this? In other words, should the formatting of the data be handled by the model, or just the data retrieval?

I know it's a nit-picky question, but I feel this is a core concept of MVC that I'm unsure of.

This post has been edited by e_i_pi: 02 September 2011 - 08:30 PM


Is This A Good Question/Topic? 1
  • +

Replies To: MVC, Business Logic, and other things that hurt my brain

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,612
  • Joined: 23-August 08

Re: MVC, Business Logic, and other things that hurt my brain

Posted 03 September 2011 - 04:12 AM

I'm a newcomer to MVC myself (latest project involves CakePHP), but I would say the view would be responsible for formatting the data in general. Perhaps an MVC guru would be along shortly to straighten me out :)
Was This Post Helpful? 1
  • +
  • -

#3 AdaHacker  Icon User is offline

  • Resident Curmudgeon

Reputation: 452
  • View blog
  • Posts: 811
  • Joined: 17-June 08

Re: MVC, Business Logic, and other things that hurt my brain

Posted 03 September 2011 - 05:40 AM

View PostJackOfAllTrades, on 03 September 2011 - 07:12 AM, said:

...I would say the view would be responsible for formatting the data in general.

You are correct, sir. When you ask how some data should look to the user, that's something that goes in the view. The model's job is to represent your data model, not format things.

View Poste_i_pi, on 02 September 2011 - 11:29 PM, said:

In other words, should the formatting of the data be handled by the model, or just the data retrieval?

One point to remember here is that while formatting data normally isn't the model's job, it's not limited to just data retrieval either. The model is really part of your domain model, i.e. the objects which represent the entities you're manipulating, and it is perfectly appropriate to put methods and logic related to your domain in the model. Forgetting this leads to the anemic domain model anti-pattern. You often see it in PHP applications where all of the logic has been shoved into the controllers and the models are little more than glorified data access objects.
Was This Post Helpful? 4
  • +
  • -

#4 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3730
  • View blog
  • Posts: 6,017
  • Joined: 08-June 10

Re: MVC, Business Logic, and other things that hurt my brain

Posted 03 September 2011 - 06:59 PM

View Poste_i_pi, on 03 September 2011 - 03:29 AM, said:

Now, the MVC pattern basically says that this should happen:
  • The controller is instantiated
  • The controller asks the model for the data
  • The controller reads in the template (the view)
  • The controller replaces the placeholders in the template with the data it got from the model
  • The controller sends (serves) this result to the end user

What you are describing there is actually more like a three-tier pattern. That is: you are passing all the communication between the presentation and data tiers through the controller, while in a MVC pattern the presentation and data tiers can communicate directly.

In practical terms, you could imagine that instead of having your controller fetch the data from the model and injecting it into the view, you would have the controller request a specific action from the view and the view would fetch the data it requires directly from the model.
Was This Post Helpful? 1
  • +
  • -

#5 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 800
  • View blog
  • Posts: 1,688
  • Joined: 30-January 09

Re: MVC, Business Logic, and other things that hurt my brain

Posted 03 September 2011 - 08:36 PM

View PostAtli, on 03 September 2011 - 07:59 PM, said:

What you are describing there is actually more like a three-tier pattern. That is: you are passing all the communication between the presentation and data tiers through the controller, while in a MVC pattern the presentation and data tiers can communicate directly.

I do actually have my framework set up so that the View can communicate directly with the Model, but since my framework is essentially a templating engine, I utilise the Controller to do the merging of data and presentation (which I believe is the right way to go). The way I've set it up, there are actually no <?php ?> tags within the views - any dynamic parts of the view get regex'd by the Controller, with placeholders in the View, and the input data for the regex coming from the Model.

Anyhow, I've restructured my framework now, and can already see the benefits of having a definite split of Model and Controller. I'm letting the Controller do the format conversion of the data, but keeping all data validation and CRUD with the Model. Now I can finally see how Models can be reusable code :)

This post has been edited by e_i_pi: 03 September 2011 - 08:36 PM

Was This Post Helpful? 0
  • +
  • -

#6 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1004
  • View blog
  • Posts: 3,562
  • Joined: 05-June 09

Re: MVC, Business Logic, and other things that hurt my brain

Posted 05 September 2011 - 01:53 AM

View Poste_i_pi, on 04 September 2011 - 04:36 AM, said:

I do actually have my framework set up so that the View can communicate directly with the Model, but since my framework is essentially a templating engine, I utilise the Controller to do the merging of data and presentation (which I believe is the right way to go). The way I've set it up, there are actually no <?php ?> tags within the views - any dynamic parts of the view get regex'd by the Controller, with placeholders in the View, and the input data for the regex coming from the Model.

I would tend to disagree with using simple replacements in your templates.

What I generally do is have template designers / writers use both short tags and alternate syntax for their loops. This makes the code less PHP-esque and a lot more understandable for designers with no knowledge to work with, for instance (yes this isn't the best):
<table>
    <tr><th>Item</th><th>Is this edible?</th></tr>
    <? foreach ($this->items as $item): ?>
        <tr><td><?= $item->Name ?></td><td><?= ( $item->IsEdible ? 'Yes' : 'No' ) ?></td></tr>
    <? endforeach ?>
</table>


Of all the designers that I have given code to so far, and generic non-technical people (ie. clients), I've never really heard a complaint.

As long as you're not using anything complex, and sticking to simple control structures such as if and foreach, there's nothing to worry about.

In summary - Not only does it give you more control over your templates and make it faster than either writing or learning a template "language", but it's also very understandable for your designers and non-technical people who may need to touch the code, as it's fairly verbose. Of course, you could also use more verbose operators, ie. and instead of && and or instead of ||.

EDIT: Note also that by using this syntax you are essentially 'semi-colonless', which makes it even more readable.

This post has been edited by RudiVisser: 05 September 2011 - 01:56 AM

Was This Post Helpful? 1
  • +
  • -

#7 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 800
  • View blog
  • Posts: 1,688
  • Joined: 30-January 09

Re: MVC, Business Logic, and other things that hurt my brain

Posted 05 September 2011 - 03:35 PM

View PostRudiVisser, on 05 September 2011 - 02:53 AM, said:

I would tend to disagree with using simple replacements in your templates.

What I generally do is have template designers / writers use both short tags and alternate syntax for their loops. This makes the code less PHP-esque and a lot more understandable for designers with no knowledge to work with, for instance (yes this isn't the best):
<table>
    <tr><th>Item</th><th>Is this edible?</th></tr>
    <? foreach ($this->items as $item): ?>
        <tr><td><?= $item->Name ?></td><td><?= ( $item->IsEdible ? 'Yes' : 'No' ) ?></td></tr>
    <? endforeach ?>
</table>


Of all the designers that I have given code to so far, and generic non-technical people (ie. clients), I've never really heard a complaint.

At my workplace, one of my tasks is to develop letter templates in RTF format that consume datasets and can contain inline C#. Essentially, it is similar to mail merge functionality of Word with an Excel spreadsheet.

Some of the issues I've experienced are:
  • The designer still has to have a working knowledge of what attributes are accessible and what their names are (e.g. - $this->myFirstname)
  • The designer still needs at least a basic working understanding of the scripting language
  • The designer can introduce poor code practice (e.g. - I inhertied a job from a co-worker who had used GOTO statements everywhere)
  • The templates will require code review by an admin/superuser that has knowledge of both the scripting language and the templating language (e.g. - PHP and HTML)
  • The line of code-separation gets blurred, meaning a template can quickly be transformed into code-heavy document
  • Reusability of templates drops significantly, as they are tightly coupled with their Controllers
  • Formatting of data has the danger of migrating towards the realm of the View, which can lead to unnecessary and unmaintainable code in the View when it comes to skinning, or other conditional display

That's not to say that this inline scripting method doesn't have it's benefits. If the developer sets up a robust data model, then the designer should have access to everything (s)he needs. It also moves design aspects away from the developer, who should only be concerned with providing visible data, not with styling that data.

I would argue though that provision of data takes precedence over display of data, or in less euphemistic words, I trust the developers more than I trust the designers. You simply can't get away from the fact that the developers and designers have to communicate closely to create the end product. But, the responsibility of tracking down errors and issues is that of the developer, and so I would prefer that the opporuntity to create errors and issues is taken away from the designers as much as possible.
Was This Post Helpful? 2
  • +
  • -

#8 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1004
  • View blog
  • Posts: 3,562
  • Joined: 05-June 09

Re: MVC, Business Logic, and other things that hurt my brain

Posted 05 September 2011 - 11:45 PM

I agree with all of your points, but to be practical there has to be a flip side to most of them too.

1 - Same goes for a replacement such as {{row_id}}
2 - Not particularly, they can be taught that <?= $row_id ?> will output that variable at a very basic level. When the template is written by the developer, they should already contain the loops / conditionals.
3 - Can't argue with that, although there does have to be regulation with everything. Designers shouldn't be using PHP at all apart from what you outline (echo/foreach/if).
4 - Hopefully the initial developer would know both to be able to review.
5 - True, but again this should be reviewed and not allowed to use anything other than the control structures you defined.
6 - This depends really. You could expose a common data model to all of your templates. Regardless though, the same goes for any replacement language as variables arn't always going to be defined.
7 - The view should be formatting your data. As per my example conditionals should be used for data display, you can't really do this anywhere else as your models should certainly represent exactly what's in the database and required to work with them in code.




What I've found in most of the environments that I've worked in - is that designers are simply not interested in things that are already there and will just get on with what they need to do.

For instance, we will provide a skin template (yes we're lazy):
<? foreach ($this->products_in_basket as $basket_product): ?>
    <?= $basket_product->name ?> - qty <?= $basket_product->qty ?><br />
<? endforeach ?>


They've never had a problem being able to fill that out. Of course, if we don't show them other properties that are exposed such as ->price, they'll probably never know they were there, but that's where both the designers and developers need to understand what's required.

This post has been edited by RudiVisser: 05 September 2011 - 11:48 PM

Was This Post Helpful? 2
  • +
  • -

#9 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 800
  • View blog
  • Posts: 1,688
  • Joined: 30-January 09

Re: MVC, Business Logic, and other things that hurt my brain

Posted 06 September 2011 - 03:41 AM

Mmm yes good points. I didn't mean to sound like I was refuting what you said in my earlier post, more just shooting the breeze over coding considerations. There's always two (or more) viewpoints when looking into things, and it helps to discuss them in forum rather than take the sometimes arduous journey of learning by experience (read: mistakes).

I suppose a better question to ask would be "Where should data manipulation/formatting lie in the Controller-View spectrum?". I am guessing that too far to either end is where you run into troubles, and the direction in which you lean may be affected by who will be involved in the project/buy the product.

With my current personal project, I am the sole coder and designer, and expect that any other staff I get on will be coders. I suppose this is why I'm leaning more towards formatting being the responsibility of the Controller, to get it to a more "coder-central" area in the product. Perhaps if I was coding with a designer's needs in mind, I would make a more designer-friendly environment.
Was This Post Helpful? 0
  • +
  • -

#10 epixeltechno  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 14-September 11

Re: MVC, Business Logic, and other things that hurt my brain

Posted 14 September 2011 - 06:24 AM

Gaining so much information from this thread.thanks man.
Was This Post Helpful? 0
  • +
  • -

#11 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3077
  • Posts: 10,789
  • Joined: 08-August 08

Re: MVC, Business Logic, and other things that hurt my brain

Posted 17 September 2011 - 04:36 PM

I've never understood why anyone would want to mix two languages together — computer language or not — or why they wouldn't expect trouble when they did. My feeling is that readability is the most important attribute any code can have, and mixing languages destroys readability. We see lots of questions here where the writer can't read their own code (if they could they wouldn't need help) and that code is less than 100 lines! Mixing languages is in my opinion the biggest reason they can't. Look at this:

Quote

<? foreach ($this->products_in_basket as $basket_product): ?>
    <?= $basket_product->name ?> - qty <?= $basket_product->qty ?><br />
<? endforeach ?>

Code like that hurts my eyes on a good day. On a bad day it practically guarantees that I'm going to make lots of mistakes. I don't need help making mistakes! That's why I wrote this code separation tutorial. It isn't intended to replace MVC, but be used with it.
Was This Post Helpful? 1
  • +
  • -

#12 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 800
  • View blog
  • Posts: 1,688
  • Joined: 30-January 09

Re: MVC, Business Logic, and other things that hurt my brain

Posted 20 September 2011 - 01:59 AM

I agree with having outright separation of languages. I've run into a share of problems doing it this way, but problems have solutions, and every method will have it's own problems I believe. It doesn't matter which road you take, you're going to have to deal with shortcomings or difficulties at some stage.

In terms of readability, and where I'm coming from, this is an example of how I template up parts of a page:
<div>
	{pMenuBar}
</div>
<div id="displayArea" class="MarginLeft10 MarginRight10">
	{pDisplayArea}
</div>


Each of the placeholders ({pMenuBar} and {pDisplayArea}) is then populated by the controller for that view. As a further example, the {pMenuBar} placeholder is populated by this template:
<div class="FloatEnd">
	<ul class="MenuBar" id="MenuBar{pId}">
		{pMenuCategories}
	</ul>
</div>


...and so on and so forth. So far, one page has as many as 15-20 unique templates, with template re-use pushing this out to as many as 40 or so templates to make up an individual page. I've found no significant slow-down doing it this way, and while the file count goes up considerably, the readability remains consistent and immediately apparent.

Serving up an entire page takes about 0.3s. This includes all templated HTML, templated Javascript, templated CSS, and DB access times (primarily for authentication). Also, I have yet to incorporate caching, which is bound to increase execution speed by a considerable amount. When you consider that about 50 files are accessed during this time, with maybe 20 of them being run through a preg_replace to serve up the template parts, I think this is working well.

For completeness, here is an example of a view-controller pair, this one serving up a button that switches the user's view between full-screen and indented-screen:
VIEW
<img id="{pId}" class="Clicky" src="{pSrc}" alt="Stretch Window Vertically">


CONTROLLER
class WindowExpander extends UI
{
	public function __construct()
	{
		// Inherit the parent constructor
		parent::__construct();

		// Populate placeholders
		$this->SetPlaceholders(
			array(
				'pId'			=>	$this->MyClass(),
				'pSrc'			=>	AOW_IMAGES_BUTTONS . $this->MyClass() . (User::IsWindowView() ? "Off" : "On" ) . FILEEXT_PNG
			)
		);
	}
}


The formatting (in this case the file name) is pushed over to the Controller, putting the onus on the programmer. I think this is a good way of going about things (for my project) as I can ensure that the design is suitably protected from misuse and mishandling of embedded scripts.

This post has been edited by e_i_pi: 20 September 2011 - 02:00 AM

Was This Post Helpful? 0
  • +
  • -

#13 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3077
  • Posts: 10,789
  • Joined: 08-August 08

Re: MVC, Business Logic, and other things that hurt my brain

Posted 20 September 2011 - 05:48 AM

View Poste_i_pi, on 20 September 2011 - 04:59 AM, said:

When you consider that about 50 files are accessed during this time, with maybe 20 of them being run through a preg_replace to serve up the template parts, I think this is working well.

From the manual:

Quote

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().

I haven't tested it, but I assume that because str_replace doesn't execute "fancy replacing rules" it is faster than preg_replace.
Was This Post Helpful? 0
  • +
  • -

#14 e_i_pi  Icon User is offline

  • = -1
  • member icon

Reputation: 800
  • View blog
  • Posts: 1,688
  • Joined: 30-January 09

Re: MVC, Business Logic, and other things that hurt my brain

Posted 20 September 2011 - 02:11 PM

View PostCTphpnwb, on 20 September 2011 - 06:48 AM, said:

From the manual:

Quote

If you don't need fancy replacing rules (like regular expressions), you should always use this function instead of preg_replace().

I haven't tested it, but I assume that because str_replace doesn't execute "fancy replacing rules" it is faster than preg_replace.

Depends on the number of elements in the replace array, and the length of the keys. I ran the numbers on several cases over 1000 repitions. Results below:
Array Length   Avg Key Length   Function      Run Time
------------   --------------   --------      --------
  2                  2          preg_replace  0.157s
  2                  2          str_replace   0.032s
  2                  15         preg_replace  0.161s
  2                  15         str_replace   0.034s
  15                 2          preg_replace  0.143s
  15                 2          str_replace   0.191s
  15                 15         preg_replace  0.182s
  15                 15         str_replace   0.200s


Was This Post Helpful? 0
  • +
  • -

#15 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 3077
  • Posts: 10,789
  • Joined: 08-August 08

Re: MVC, Business Logic, and other things that hurt my brain

Posted 20 September 2011 - 02:21 PM

Interesting, but I think you might want to try 10,000 or 100,000 repetitions because your results are so close.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2