I'm learning Yii. I have a test development which contains a number of tables (employee, personalDetails, address). My understanding of MVC leads me to see these almost as individual planets, where each (MVC) component plays a clearly defined role within that world.
I have a question that’s starting to bug me because I now want to pass requests for data and calculations between these worlds. I have come across a few postings on how to do this, but they appear more like “hacks” than “prescribed” practises. I’m obviously keen not to pick up bad habits. This kind of process is obviously a root requirement of any development so would like to ask for some guidance on this.
A specific example would be to return a view of employees who have take home salaries > $100,000 including bonuses ( e.g. employee controller asks personalDetails controller to calculate {goss salary + bonuses – tax} and return all appropriate instances, it then looks up and returns the relevant employees).
So do I create a function in personalDetails and call it from inside employee controller, or should this kind of thing go in an extension ... or is there another approach?
I’d appreciate your guidance on this
For encapsulated self managed view parts use widgets. For above case you could create widget with configurable treshhold.
If you have to ask different controller to calculate something it is a bad practice. Place such calculations in model instead. Model is highly reusable, view can be reused, however controller should only respond to action and bind data to view.
Fat model, thin controller, wise view.
Here is some draft code:
First create model with any needed calculations:
class Employee extends CActiveRecord
{
public function getTotalSalary()
{
// Do any calculations here
// ...
return $salary;
}
}
Then you can reuse it in controllers:
class FirstController extends CController
{
public function actionPersonDetails()
{
$model = $this->_loadModel();
// By assigning this you will have getTotalSalary() available in view
$this->render('personDetails', ['model' => $model]);
}
}
class SecondController extends CController
{
public function actionViewSallary()
{
$model = $this->_loadModel();
// Also here you will have getTotalSalary() available in view
$this->render('viewSallary', ['model' => $model]);
}
}
And for more complex scenarios where you need something standalone create widget:
class EmployeesWidget extends CWidget
{
public $minSalary = 0;
private $_data = null;
public function init()
{
$this->_data = new CActiveDataProvider(/* Criteria here with $this->minSalary as param */);
}
public function run()
{
$this->render('employeesWidget', ['data' => $this->_data]);
}
}
Then you can easy use it in any view, even in other widgets:
$this->widget('path.to.EmployeesWidget', [
'minSallary' => 10000
]);
Related
I have a little problem. What data keep in controllers and what in models? I know in models keep whole logic of applications etc, but what's query and helpers functions? for example
Controller:
public function add(Request $request)
{
$item = new Item()
$item->name = $request->name;
$item->save();
$this->makeDirectory();
}
private function makeDirectory()
{
//make a directory with photo this product
}
Where should I keep "makeDirecory" method in controller or models?
This is another situation when i would delete product and reference from another table.
public function delete(Items $id)
{
$id->delete();
$this->deleteProperties($id->properties); // $id->properties is a method from Items model with references to table Properties
}
private function deleteProperties(Properties $id)
{
$id->delete();
}
Should I keep "deleteProperties" method in controller, Items model or Properties model? and invoke this method from this model?
You should keep methods like makeDirectory() in a service class and call it with:
$this->fileService->makeDirectory($directory);
You should keep data related logic in model classes or repository classes and use it in controller with:
$this->model->getSomeData();
You may also want to google "Fat models, skinny controllers".
Regarding helper functions, you should use these only when you really need one. For example, isAdmin() is a very handy global helper, but you should never create helpers like getAllUsers() or Helpers::getAllUsers()
I use controllers only to validate the incoming data and passing data to views.
I add another layer of classes that I call Departments. So, I have a department for profiles, artiles, info pages etc. Each department has its own namespace and a set of classes connected with the functionality.
Always think about SoC - separation of concerns. If you put a lot of logic into a controller, it will eventually get huge, hard to maintain and extend.
Example:
Controller:
public function addItem (Request $request, Item $item, ItemStorage
$itemStorage) {
if ($item->verifyInput($request->all())) {
$itemStorage->createItem ($item, $request->all());
}
else {
// ... handle input error
}
// ... view
}
App\Departments\Items:
class ItemStorage {
public function createItem ($newItem, $attributes) {
$newItem->create($attributes);
// ... prepare data for creating a directory
$this->makeDirectory($directoryName);
}
private function makeDirectory ($directoryName) {
//... create directory
}
}
You can/should separate the tasks even further. ItemStorage might not need to handle actual directory creation. You can call another department/service class name e.g. DiskManagement. This department would contain Classes like FileSystem. So, inside the makeDirectory() method, you would call a method from a class specialized in file system operations.
Hi I am trying to build a to do list in Laravel. It's my first time with a framework. I have actually read a lot of articles about MVC but I don't understand the meaning of model enough, and I want to learn this the correct way. So I have this code and I didn't know where to place it, in a controller or in a model?
public function getTask()
{
$tasks = DB::table('tasks')->get();
foreach ($tasks as $task) {
var_dump($task->name);
var_dump($task->description);
}
}
public function deleteTask($id)
{
DB::table('tasks')->where('id',$id)->delete();
}
public function updateTask($id)
{
DB::table('tasks')
->where('id',$id)
->update(['votes' => 1]);
}
public function createTask($name,$slug,$description)
{
DB::table('tasks')->insert(
['name' => $name],
['slug' => $slug],
['description' => $description]
);
}
I am a very new with frameworks so please be patient with my question.
the main role of models is to abstract the database layer to the framework (it is the class that talks to the database), so theoretically speaking, you would only use models to query the database (with active record class or native SQL) and return the result to the controller and the controller will do all the logic work (if...else...etc.) then send it to the view or call a model again to talk to the database ,BUT it is not uncommon in real life to see some logic code in the model althought it is considered as a bad practice in MVC world .you can read more about models for laravel here http://laravel.com/docs/5.1/eloquent
The code your showing goes in a controller.
Simply said: A model represents your table in your Database and could look as simple as this (User.php);
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
//
}
The controller has the logic implementation necessary to read and modify the view through the model.
The model represents all the information that the user can control so it enables the controller access to the view and the view access to the controller, which is called as data-binding.
My goal of asking this question is to ferret out whether there are benefits to injecting Controller directly with the data it needs (more specific approach) opposed to injecting a Model into a Controller (more generic approach). Or to establish whether or not it is just a matter of preference.
Injecting Controller with Model:
Model can be used to run all kinds of queries to retrieve various bits of data, but it is a heavier-weight construct than the data itself. Model essentially contains data, or at least it can access all the data you may need. Example:
class CategoryControllerWithModel
{
private $model;
public function __construct($model)
{
$this->model = $model;
}
// generates HTML for input form
public function genHtml()
{
/* retrieve data */
$categories = $this->model->getCategories();
//...
}
}
//instantiation within Factory Method:
class Factory
{
$model = new CategoryModel();
$controller = new CategoryControllerWithModel($model);
return $controller;
}
Injecting Controller with Data:
Here we do a bit more upfront with in the Factory method but we get a leaner Controller that only receives exactly the data it needs and is so completely separated from the Model that it is not even aware of its existence.
class CategoryControllerWithData
{
private $categories;
public function __construct($categories)
{
$this->categories = $categories;
}
public function genHtml()
{
$categories = $this->categories;
}
}
//instantiation within Factory Method:
class Factory
{
$model = new CategoryModel();
//a bit more work to get the data Controller needs
//benefit: Controller not tied to the Model
$categories = $model->getCategories():
$controller = new CategoryControllerWithData($categories);
return $controller;
}
Question:
I suppose MVC stands for exactly that -- Model, View, Controller, so injecting Model is probably considered to be an "okay" thing to do. If so, am I taking this too far by trying to remove Controller dependency on Model?
Suppose I insist that I want to inject Data into my Controllers rather than the Model. Is this a purely preferential issue do you see any concrete benefits of doing so?
From my point of view, Factory shouldn't be responsible for domain logic. It should only be responsible for building things up.
In this case, where you are injecting data, Factory has to know what categories controller is searching for, are there any filtering and so on.
So I think for controller you should only inject model, keep Factory single responsibility only for building things and controller should be responsible for it's data.
I think it's a matter of "separation of concerns" also I do not think that would be a good example of using MVC. I would think more along these lines:
class FooController
{
public function actionView($alias){
$category = Category::loadByAlias($alias);
..... load and render layouts etc .....
}
public function actionList(){
$categories = Category::loadAll();
..... etc ......
}
}
like this the neither the Controller nor the Factory need to know what needs to be done when you load a category nor do they have to handle active/inactive status, even User access ... etc this is all Model Logic, Model can have beforeLoad and afterLoad functions, conditions for listing all categories, eager or lazy loading of related models etc...
I have a question about making some elements available in any view file
Lets say im building a webshop and on every page i will be having my sidebar, shoppingcart, user greeting in the top.
How can i make these things available in all my view files?
I could make a class, lets say class Frontend
I could do something like this:
class Frontend {
static $me;
public function get(){
if(!self::$me){
self::$me = new self();
}
return self::$me;
}
private function getShoppingCart(){
// do things
}
public function getData(){
return array(
'Username' => User::find(1)->UserName,
'Cart' => $this->getShoppingCart()
);
}
}
Now in my controller i could pass this Frontend object into the view
View::make('file.view')->with(array('data' => Frontend::get()->getData()));
But this way i will end up with a god class containing way too much stuff and in every controller method i would have to pass these data, which is not relevant to the controller method
Is there a way in Laravel that makes specific data available across all view files?
Thanks!
Use share:
View::share('name', 'Steve');
as per http://laravel.com/docs/responses#views
To keep everything clean, every part of the page should be its own *.blade.php file which would be put together using a master template of sorts.
master.blade.php
#yield('includes.sidebar')
#yield('users.greeting')
#yield('store.shoppingcart')
Then you can use view composers so that each time these views are loaded, the data you want is injected into them. I would probably either create a new file which would get autoloaded, or if you have service providers for the separate portions of your app that these views would use, it would also go great in there.
View::composer('users.greeting', function($view)
{
$view->with('user', Auth::user());
});
In this case, it would make the user model available inside your view. This makes it very easy to manage which data gets injected into your views.
You are close with your 'god class' idea.
Setting a $data variable in a basecontroller has helped me with similar issues
class BaseController extends Controller {
protected $data;
public function __construct() {
$this->data['Username'] = User::find(1)->UserName
$this->data['Cart'] = $this->getShoppingCart()
}
}
class Frontend extends BaseController {
function someMethod(){
View::make('file.view', $this->data)
}
}
My Index page uses 3 tables in the database:
index_slider
index_feature
footer_boxes
I use one controller (IndexController.php) and call the three models like so:
public function index() {
return View::make('index')
->with('index_slider', IndexSlider::all())
->with('index_feature', IndexFeature::all())
->with('footer_boxes', FooterBoxes::all());
}
The three models above need ::all() data, so they are all setup like this:
class IndexSlider extends Eloquent {
public $table ='index_slider';
}
note: class name changes for each model
Seeing as my index page requires these 3 tables and the fact I am repeating the syntax in each model then should I be using polymorphic relations or setting this up differently? ORM from what I have read should have 1 model for each table, but I can't help but feel this would be silly in my situation and many others. DRY (don't repeat yourself) looses meaning in a sense.
What would be the best approach to take here or am I on the right track?
Firstly I should say each model is written for a specific table, you can't squeeze three tables into one model unless they are related. See Here
There are two ways I would go about making your code more DRY.
Instead of passing your data in a chain of withs I would pass it as the second parameter in your make:
public function index() {
$data = array(
'index_slider' => IndexSlider::all(),
'index_feature' => IndexFeature::all(),
'footer_boxes' => FooterBoxes::all(),
);
return View::make('index', $data);
}
Passing data as the second parameter. See here
The other way I would go about it, and this is a better solution if your application is going to grow large, is to create a service (another model class but not hooked up to eloquent) that when you call will return the necessary data. I would definitely do it this way if you are returning the above data in multiple views.
An example of using a service would look something like this:
<?php
// app/models/services/indexService.php
namespace Services;
use IndexSlider;
use IndexFeature;
use FooterBoxes;
class IndexService
{
public function indexData()
{
$data = array(
'index_slider' => IndexSlider::all(),
'index_feature' => IndexFeature::all(),
'footer_boxes' => FooterBoxes::all(),
);
return $data;
}
}
and your controller:
<?php
// app/controllers/IndexController.php
use Services/IndexService;
class IndexController extends BaseController
{
public function index() {
return View::make('index', with(new IndexService())->indexData());
}
}
This service can be expanded with a lot less specific methods and you should definitely change the naming (from IndexService and indexData to more specific class/method names).
If you want more information on using Services I wrote a cool article about it here
Hope this helps!