Do extremely simple tables still require their own model class? - php

I've been using laravel (php mvc framework) for a few weeks now. Currently I am creating a model for every single non-pivot table. Even tables as simple as:
id (unsigned int (PK)) | usertype (varchar(20))
1 | guest
2 | member
3 | Moderator
Because it makes it easier to relate my other models to them using the eloquent ORM.
I was wondering if its normal to create models for such simple tables for the sake of utilizing an ORM or if there is a better approach?
Currently my application is functioning using models for these tables, but I still want to make sure I am picking up good coding conventions while I'm learning.
Thanks in advance.

Here comes the long answer: YES!
I don't know when or why model became a synonym to entity, but this leads to confusion.
According to MVC inventor, Trygve Reenskaug, in the original MVC article:
DEFINITION
A Model is an active representation of an abstraction in the form of data in a computing system
[...]
The models are represented in the computer as acollection of data together with the methods necessary to process these data.
So, many people nowadays define (incorrectly) models as data representation, or the data storage or something else, but this is wrong.
Model deals with your application logic and this INCLUDES data abstraction, data storage, data processing, etc.
I use to call my data abstractions an Entity instead of model. My application model layer is called Service or Application Model. My storage layer is called just Storage and so on... All of this togheter is what we can call Model
That being clarified, now we can go on...
You said:
Because it makes it easier to relate my other models to them using the eloquent ORM.
That's enough!
Nothing keeps you away from using plan txt files as storage, but if your data relate to others, then you should look for a database.
Eloquent is an ORM (Object-Relational Mapping) and so, it relies on a database behind it. If you use txt files, how would do to recover users by their user type?
I'm not used to frameworks, but most of them generate entities automatically, you just need to declare them...
If some entity has no business logic and you just need to store it, so you don't need a "full model" for it. And that's what you're doing.
Hope I convinced you...

Related

Models in Laravel 5

I'm doing a web app here using Laravel + AngularJS and I have a question.Do I need a model for each table that I have in my database? There are 87 tables in my database and I need to query all of them according to with the input that the User wants.
I just want to make sure with all tables must have a model file or if just one is enough.
There are 2 ways by which you can access your DB tables:
Eloquent ORM (dependent on Models)
DB Facade Query Builder(independent on Models)
Former, is more clean and best approach to perform DB query and related task, whereas latter is not clean, and it is going to be difficult for you to manage large application, as you told there are 80+ tables in your application.
Also, if you're using Eloquent way, then it's also a better to have a base model, which will have common code which you can inherit in child models. Like if you want to store "user id" who did some DB changes, then in the boot function, you can write Auth::id() and assign that value to changed_by field on your table.
In DB Facade way, you've to hard code table name every time you're performing DB operation, and which leads to inconsistency when you found that you've to change the name of the table, it's a rare scenario still it'll be difficult to manage if in a file there are multiple tables DB operation going on. There are options like, creating a global table name variable which can be accessed to perform DB operation.
Conclusion:
Yes, creating 80+ model for implementing Eloquent way is painful, but for a short term, as the application grows it will be easy for you to manage, it will be good for other developer if they start working on it, as it will give a overview of DB and it will improves code readability.
It depends on how you'd like to handle queries.
If you'd like to use Eloquent ORM, you need model classes to handle objects and relationships. That is a model for a table, except intermediate relationship tables, which may be accessed through pivot attribute.
Raw SQL queries are also supported. You don't really need model classes for them, as each result within the result array will be a PHP StdClass object. You need to write raw SQL though.
See Laravel documentation.

Where to put custom SQL code in CakePHP 3?

I'm building an application in CakePHP 3. It uses a number of legacy databases which are not built in the Cake conventions.
I do not want to use any of the ORM features Cake provides, as it's more tedious to set up all the relations than just write "Raw SQL". We are also not going to make any changes to the database structures, so the ORM is a non-starter. So I'm going to write raw SQL queries for everything.
However, I'm not sure where this code would be put. I've read https://book.cakephp.org/3.0/en/orm/database-basics.html#running-select-statements but it doesn't say where you actually put that code.
I don't want to put my queries in a controller ideally since that defeats the purpose of MVC.
All I really need is one Model where I can put all my queries in different functions and reference them in my Controller(s).
In Cake 2.x it was easy to just create a model under app/Model/ then load it (loadModel) where needed in controller(s). But with the new Cake 3.x Table and Entity spaces, I'm not sure how this fits in?
I've also read up on Modelless Forms but don't think they're right either. For example the initial page of the application shows a list of chemicals which is just a SELECT statement - it doesn't involve forms or user input at all at this stage.
Obviously there will also be situations where I need to pass data from a Controller to the Model, e.g. queries based on user input.
As mentioned in the comments, I would suggest to not ditch the ORM, it has so many benefits, you'll most probably regret it in the long run.
Setting up the tables shouldn't be a big deal, you could bake everything, and do the refactoring with for example an IDE that does the dirty work of renaming references and filenames, and then set up the rules and associations manually, which might be a little tedious, but overally pretty simple, as there shouldn't really be much more to configure with respect to the database schema, than the foreign keys, and possibly the association property names (which might require updating possible entities #property annotations too) - maybe here and there also conditions and stuff, but oh well.
That being said, for the sake of completeness, you can always create any logic you want, anywhere you want. CakePHP is just PHP, so you could simply create a class somewhere in say the Model namespace (which is a natural fit for model related logic), and use it like any other class wherever needed.
// src/Model/SomeModelRelatedClass.php
namespace App\Model;
class SomeModelRelatedClass
{
public function queryTheDatabase()
{
// ...
}
}
$inst = new \App\Model\SomeModelRelatedClass();
$results = $inst->queryTheDatabase();
See also
Cookbook > Database Access & ORM > Associations - Linking Tables Together > BelongsTo Associations

implementing my first PHP model

I've written a small RESTful PHP backend using the Slim framework (http://www.slimframework.com/) that interfaces with a MySQL database, and right now I just have one class doing all the DB interactions and it's getting kinda big. So it's time to organize it a little more cleanly.
So based on what I understand from MVC, a better way to do this might be to implement a model layer like so:
each logical entity in the system will be implemented with a data class. I.E. user accounts: a class called "Account" with getId(), getName(), getEmail(), etc etc
and corresponding factory objects, i.e. AccountFactory which owns the DB connection and creates an Account class to manipulate elsewhere in the business logic layer.
The business logic layer would still be pretty simple, maybe a class called MyApplication that instantiates factories and uses them to respond to the RESTful API calls.
Business logic might be, for example, matching two accounts together based on geographical location. So in this case, I would just be testing on the data in two separate Account objects instead of the raw data loaded from the database.
But that seems like a lot of refactoring time spent to do basically the same thing. Why wouldn't I want to just use the plain array data I load from the database? It's not DB-independent, sure, but I don't really plan on switching away from MySQL at the moment anyway.
Am I approaching this in the correct way?
Well, partly.
The first point describes a model - the M in MVC. Abstracting your "business logic" from this model makes sense in many ways. One use case could be a website that interacts with the same data as the REST API. You could reuse the model and only need to build new controllers.
The "business logic"/"layer" would probably the controller - the C in MVC. However I would not give the factory objects ownership of the DB connection, as some use cases may want to use multiple factory objects but should use the same database connection...
I suggest you read more about the structure and pro's and con's of the MVC approach.
when you start from scratch the best is to :
have a ORM (which mean that you must have relations in your MySQL database with foreign keys etc.). Thats very quick way to manage database management in your program.
Create your home-made class for each entitiy = 1 class.
The best pratices are generally to have an ORM but it can be a bit heavy (it depends on your architecture and application).
In your case put an ORM seems to be a lot too much cause you developped a lot.
It depends of the future of your application : will it grow again ? will a lot of developper will develop on it ?
For a small/medium size you can easily refactor a bit your class by big theme, ex : 1 class for your 3 biggest entity in which you have the more requests. That will tidy a bit the mess and organize things, and then you can migrate your new classes for eqch new entity. For the old ones you can migrate step by stepm or not
Another good practice is to have getters and setters $this->getter_id(); $this->setter_id( $in_nId ); That will help you a lot if you need to change some db fields

in Zend, Why do We use DB Model class and Mapper class as two separate?

I am working on the zend project, I am referring on other zend project to create the new Zend Project.But I don't like to blindly follow that project without understanding. In the Zend Directory structure, In Model class there are mainly two type of classes I see, like as in
- models
- DbTables
- Blog.php //Extends Zend_Db_Table_Abstract
- Blog.php // Contains methods like validate() and save()
- BlogMapper.php // Also Contains methods like validate(Blog b) & save(Blog b)
Why this specific structure is followed?
Is this is to separate Object class and Database model class?
Please explain.
DataMapper is a design pattern from Patterns of Enterprise Application Architecture.
The Data Mapper is a layer of software that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. With Data Mapper the in-memory objects needn't know even that there's a database present; they need no SQL interface code, and certainly no knowledge of the database schema.
How you store data in a relational database is usually different from how you would structure objects in memory. For instance, an object will have an array with other objects, while in a database, your table will have a foreign key to another table instead. Because of the object-relational impedance mismatch, you use a mediating layer between the domain object and the database. This way, you can evolve both without affecting the other.
Separating the Mapping responsibility in its own layer is also more closely following the Single Responsibility Principle. Your objects dont need to know about the DB logic and vice versa. This gives you greater flexibility when writing your code.
When you dont want to use a Domain Model, you usually dont need DataMapper. If your database tables are simple, you might be better off with a TableModule and TableDataGateway or even just ActiveRecord.
For various other patterns see my answer to
ORM/DAO/DataMapper/ActiveRecord/TableGateway differences? and
http://martinfowler.com/eaaCatalog/index.html
The idea of a Model is to wrap up the logical collection of data inside of your code.
The idea of a DataMapper is to relate this application-level collection of data with how you are storing it.
For a lot of ActiveRecord implementations, the framework does not provide this separation of intent and this can lead to problems. For example, a BlogPost model can wrap up the basic information of a blog post like
title
author
body
date_posted
But maybe you also want to have it contain something like:
number_of_reads
number_of_likes
Now you could store all of this data in a single MySQL table to begin with, but as your blog grows and you become super famous, you find out that your statistics data is taking an awful lot of hits and you want to move it off to a separate database server.
How would you go about migrating those fields of the BlogPost objects off to a different data store without changing your application code?
With the DataMapper, you can modify the way the object is saved to the database(s) and the way it is loaded from the database(s). This lets you tweak the storage mechanism without having to change the actual collection of information that your application relies on.

Designing a Zend model for multiple tables together?

i am using Zend Framework to build a web interface for setting up ACL - permission rights - for users of a custom CMS. Since the ACL data is spread in 5 tables(users, groups, permissions, urls=action+controller, nice permission name for the user to understand) and i have only one controller with the four basic CRUD(create, list, update, delete) operations i was wondering what is the best way to do it?
All the examples in my books i've seen that each model extend Zend_Db_Table_Abstract and thus represents one table.
I was thinking i have to do a model that doesn't extend zend_db_table_abstract and then write the queries that i need by hand thus limiting myself to mysql database only?
p.s. please do not argue over the acl database structure
thank you
The definition of the Table Data Gateway pattern is
An object that acts as a Gateway to a database table. One instance handles all the rows in the table.
That's why you won't see it used any differently in Zend Framework. It's a Data Source Architectural Patterns while the thing you are asking about is a Domain specific class.
What you are encountering is Impedance Mismatch, meaning your Business Objects dont match the structure of your Database Design. The common solution is to use a DataMapper or an ORM to handle that for you.
The other solution would be to create a View in your database that joins the tables in a way that maps 1:1 to your required business objects. Then add a Zend_Db_Table for that view. You'd still have to come up with custom create, update, delete logic though. That's not data mapping though, but if you don't have any Business/Domain classes to map to, it's fine.

Categories