Deprecation of TableRegistry::get() - cakephp

I'd like to ask what are your thought on deprecation of the TableRegistry::get() static call in CakePHP 3.6?
In my opinion it was not a good idea.
First of all, using LocatorAwareTrait is wrong on many levels. Most important, using traits in such way can break the Single Responsibility and Separation of Concerns principles. In addition some developers don't want to use traits as all because they thing that it breaks the object oriented design pattern. They prefer delegation.
I prefer to use delegation as well with combination of flyweight/singleton approach. I know that the delegation is encapsulated by the LocatorAwareTrait but the only problem is that it exposes the (get/set)TableLocator methods that can be used incorrectly.
In other words if i have following facade:
class Fruits {
use \Cake\ORM\Locator\LocatorAwareTrait;
public function getApples() { ... }
public function getOranges() { ... }
...
}
$fruits = new Fruits();
I don't want to be able to call $fruits->getTableLocator()->get('table') outside of the scope of Fruits.
The other thing you need to consider when you make such changes is the adaptation of the framework. Doing TableRegistry::getTableLocator()->get('table') every time i need to access the model is not the best thing if i have multiple modules in my application that move beyond simple layered architecture.
Having flyweight/singleton class like TableRegistry with property get to access desired model just makes the development more straight forward and life easier.
Ideally, i would just like to call TR::get('table'), although that breaks the Cake's coding standards. (I've created that wrapper for myself anyways to make my app bullet proof from any similar changes)
What are your thoughts?

Related

Proper way of handling scopes with pivot involved

As a laravel user for a couple of months now, I'm trying to better understand advanced use of Eloquent.
I ran into a case where I can't come up with a solution that feels right.
I've got the following structure (simplified)
Mandate
id
status_id
Mandate_user
mandat_id
user_id
link_status
User
id
I declared belongsToMany in both User and Mandat via the pivot table.
on User:
public function mandates(){
return belongsToMany(..)->withPivot('link_status');
}
I'm able to get accepted mandates for a user by using
public function acceptedMandates(){
return $this->mandates()->wherePivot('link_status', MandateUserStatus::Accepted);
}
This works but I'm wondering if there would be a better way by using scopes or other eloquent methods.
And I'm trying to get accepted mandates that also have a status_id lower than 4 (which comes from an enum as well)
I thought of something like :
public function runningMandates(){
return $this->acceptedMandates()->where('status_id','<', 4);
}
Then gathering mandates like so:
$mandates = User::find(1)->runningMandates();
But would the eloquent way be of doing something like:
$mandates = User::find(1)->mandates()->running()->accepted();
Thanks for your time.
It's a very subjective question and hard to give a straight answer to, but hopefully I can stop you from second-guessing yourself: what you're doing is perfectly fine and no less "eloquent-like" than the other.
Personally I like what you're doing now much more than what you present as the "Eloquent way" and have done so before in professional projects, but ultimately there is a difference in the way you design the code for a framework or package, which must be flexible to account for many different scenarios, most of which you cannot even envision when doing version one, versus how you design the code for an app which will only be consumed by itself. If you know the business logic that drives your app and the views it will present to its users (subsequently, the queries it must perform), why wouldn't you create methods that will easily achieve just that?
Eloquent relies on chaining not just because it's cool, but because it does not know (or care to know) what your business logic is. To me, the "Eloquent way" is more about fluent, readable code, and I find that $user->runningMandates is more readable than $user->mandates()->running()->accepted()->get().
I also find that the first approach is easier to get into. If you're constantly forcing yourself to separate methods so they can be chained, it can be harder to grasp which method is doing what and which method relies on which. Query scopes can modify the query as they like (join, alias, etc) so the danger lies in one method requiring another to come first, because you're conditioning based on a table or column that isn't on the original query, so a method will only work in conjunction with another; or maybe two methods are trying to join the same table, or using the same aliases, so they cannot be used together. It may seem far-fetched, but often the effort to keep things separate and tidy will make your code harder to use. But even if things don't blow up code-wise, the deal-breaker to me would be neglecting business logic: in your case, does it make sense to have two separate scopes for running and accepted? Can a mandate be running if it's not accepted? If not, you should try to prevent a less knowledgeable developer from creating that flawed query (logic-wise). And as you said, the structure is simplified so there may be other gotchas lurking around, and many more will come as the app grows in complexity.
If I'm taking over someone else's code, I'd rather have limited, self-contained methods that don't break over simple, decentralized methods that require you to read (often non-existent) documentation in order to prevent the many ways in which to mis-use them.
Basically, scopes add constraints to the query so you may use the scope approach to modify the query by calling scope methods that will eventually give you a chance to make a query dynamically. So, you may declare (as you did) one relationship method where you may do all the query and call that specific method or use scope methods two build the query using method calls where each method adds a constraint. In this case, it'll be more dynamic but still it's a preference and it gives you more flexibility (IMO). So yes, you can use query scopes for that, for example:
// Declare the main relationship
public function mandates()
{
return $this->belongsToMany(..)->withPivot('link_status');
}
Now, declare query scope for accepted (add a constraint on the query returned by mandates method call)
public function scopeAccepted($query)
{
return $query->wherePivot('link_status', MandateUserStatus::Accepted);
}
Now, add another query scope for running, for example:
public function scopeRunning($query)
{
return $query->where('status_id','<', 4);
}
Now, if you call something likethe following:
$user = User::find(1);
Now, call the relationship method (not as property)
$mendates = $user
->mandates() // The method is called and a query object is constructed
->running() // Add another constraint into the query: ->where('status_id','<', 4)
->accepted() // Add another constraint into the query: ...
->get(); // Finally, execute the query to get the result
Probably, it's clear to you now. Notice the method call mandates(), it's a method call on the relation defined which returns the Query Builder and by chaining additional scope method calls, you are just modifying the query by adding some more constraints but you can do all the query in one method without dynamic scopes, so it's up to you. While, scopes gives you more flexibility but it doesn't mean you've to follow this approach always, it depends.

Cakephp 3: Calling Table functions from Entity is a bad or good idea?

When I have some entity and I wanna save, validade or delete. Why do I have to call the Table method? For example:
$articlesTable = TableRegistry::get('Articles');
$article = $articlesTable->get(12);
$article->title = 'CakePHP is THE best PHP framework!';
$articlesTable->save($article);
Why isn't like this:
$article->save();
or $article->delete();
It's very simple to implement:
On my Article Entity I can do it like:
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Article extends Entity
{
public function save()
{
$table = TableRegistry::get($this->source());
$table->save($this);
}
}
It's working, but I would like to know if its a bad practice or a good idea.
Thanks in advance :)
TL;DR: Technically you can do it for the high price of tight coupling (which is considered bad practice).
Explanation: I wouldn't consider this best practice because the entity is supposed to be a dumb data object. It should not contain any business logic. Also usually it's not just a simple save call but there is some follow up logic to implement: Handle the success and failure of the save and act accordingly by updating the UI or sending a response. Also you effectively couple the entity with a specific table. You turn a dumb data object into an object that implements business logic.
Technically you can do it this way and I think there are frameworks or ORMs that do it this way but I'm not a fan of coupling things. I prefer to try to write code as lose coupled as possible. See also SoC.
Also I don't think you'll save any lines of code with your approach, you just move it to a different place. I don't see any benefit that would justify the introduction of coupling the entity to the business logic.
If you go your path I would implement that method as a trait or use a base entity class to inherit from to avoid repeating the code.

Kotlin Nested Object Classes

Ok so i'v been starting to learn kotlin for a week now, and i love the language:p
Besides the great utility of extension function, i feel like they lack a proper way of creating namespaces like java utility classes (xxxUtil).
I have recently starting to use this aproach, which im not sure is the right one, and i would like some feedback from Kotlin experienced users.
Is this a valid and proper thing todo:
object RealmDb {
private val realmInstance by lazy{ Realm.getInstance(MainApplication.instance) }
private fun wrapInTransaction(code:() -> Unit){
realmInstance.beginTransaction();
code.invoke()
realmInstance.commitTransaction();
}
object NormaNote{
fun create(...) {...}
fun update(...) {...}
}
}
So, whenever i want to update some NormalNote value to a Realm Database, i do the following:
RealmDb.NormaNote.create(title.text.toString(), note.text.toString())
Is this a common thing to do? Are there better approaches? As i understood, this is singleton nesting, i don't think there's any problem with this, i just don't like to put this common things like DB operations inside classes that need to be instantiated. In old java i opted to static classes
The officially recommended way to create namespaces in Kotlin is to put properties and functions that don't need to be inside classes at the top level of the file, and to use the package statements to create a namespace hierarchy. We see the practice of creating utility classes in Java as a workaround for a deficiency in the language, and not as a good practice to be followed in other languages.
In your example, I would put all of the code in top-level functions and properties.
I don't know about the rest of the code, but I do know that you don't have to call .invoke () on code. The invoke method can always be shortened to a direct call, which in this case would be code ().

Is ReactiveUI Production Ready?

I've been looking into the feasability of using Reactive UI in production code. Some of the features are really appealing, but I have concerns about taking a dependency on this library. These include:
Whacky naming and conventions. For example, protected members starting with lower case, and the RaiseAndSetIfChanged method depends on your private member beginning with an underscore. I understand Paul Betts (ReactiveUI author) has a Ruby background, so I guess that's where the odd naming stems from. However, this will cause a real issue for me, since standard naming (as per Stylecop) is enforced throughout my project. Even if it wasn't enforced, I'd be concerned by the resultant inconsistency in naming that this will cause.
Lack of documentation/samples. There is some documentation and a lonely sample. However, the documentation is just a series of (old) blog posts and the sample is based on V2 of the library (it's now on V4).
Odd design, in parts. For example, logging is abstracted so as not to take a dependency on a specific logging framework. Fair enough. However, since I use log4net (and not NLog) I will need my own adapter. I think that will require me to implement IRxUIFullLogger, which has a metric crapload of methods in it (well over 50). I would have thought a far better approach would be to define a very simple interface and then provide extension methods within ReactiveUI to facilitate all the requisite overloads. In addition, there's this weird IWantsToRegisterStuff interface that the NLog assembly depends on, that I won't be able to depend on (because it's an internal interface). I'm hoping I don't need that...
Anyway, my concern here is the overall design of the library. Has anyone been bitten by this?
I'm already using MVVM Light extensively. I know Paul did a blog post where he explains you can technically use both, but my concern is more around maintainability. I suspect it would be horribly confusing having both intermingled in one's code base.
Does anyone have hands-on experience with using Reactive UI in production? If so, are you able to allay or address any of my above concerns?
Let's go through your concerns piece by piece:
#1. "Whacky naming and conventions."
Now that ReactiveUI 4.1+ has CallerMemberName, you don't have to use the conventions at all (and even then, you can override them via RxApp.GetFieldNameForPropertyFunc). Just write a property as:
int iCanNameThisWhateverIWant;
public int SomeProperty {
get { return iCanNameThisWhateverIWant; }
set { this.RaiseAndSetIfChanged(ref iCanNameThisWhateverIWant, value); }
}
#2. Lack of documentation/samples
This is legit, but here's some more docs / samples:
http://docs.reactiveui.net/ (this is the official ReactiveUI documentation, a work in progress but definitely where you want to start)
https://github.com/reactiveui/ReactiveUI.Samples
https://github.com/reactiveui/RxUI_QCon
https://github.com/play/play-windows
#3. "I would have thought a far better approach would be to define a very simple interface and then provide extension methods within ReactiveUI to facilitate all the requisite overloads"
Implement IRxUILogger instead, it has a scant two methods :) ReactiveUI will fill in the rest. IRxUIFullLogger is only there if you need it.
"In addition, there's this weird IWantsToRegisterStuff interface "
You don't need to know about this :) This is only for dealing with ReactiveUI initializing itself so that you don't have to have boilerplate code.
"I suspect it would be horribly confusing having both intermingled in one's code base."
Not really. Just think of it as "MVVM Light with SuperPowers".
I am answering as someone who has used ReactiveUI in a few production systems, has had issues with the way RxUI does stuff, and has submitted patches to try and fix issues I've had.
Disclaimer: I don't use all the features of RxUI. The reason being I don't agree with the way those features have been implemented. I'll detail my changes as I go.
Naming. I thought this was odd too. This ended up being one of the features I don't really use. I use PropertyChanged.Fody to weave in the change notification using AOP. As a result my properties look like auto properties.
Doco. Yes there could be more. Especially with the newer parts like routing. This possibly is a reason why I don't use all of RxUI.
Logging. I've had issues with this in the past. See pull request 69. At the end of the day I see RxUI as a very opinionated framework. If you don't agree with that opinion you can suggest changes, but that's all. Opinionated does not make it bad.
I use RxUI with Caliburn Micro. CM handles View-ViewModel location and binding, Screen and Conductors. I don't use CM's convention binding. RxUI handles Commands, and ViewModel INPC code, and allows me to react to property changes using Reactive instead of the traditional approaches. By keeping these things separate I find it much easier to mix the two together.
Does any of these issues have anything to do with being production ready? Nope. ReactiveUI is stable, has a decently sized user base, problems get solved quickly in the google group and Paul is receptive to discussion.
I use it in production and so far RxUI has been perfectly stable. The application has had problems with stability, some to do with EMS, others with an UnhandledException handler that was causing more problems than it was solving, but I've not had any problems with the ReactiveUI part of the application. However, I have had issues regarding the ObservableForProperty not firing at all, which I may have used incorrectly and did work consistently (incorrectly) in my test code as well as in the UI at run time.
-1. Paul explains that the _Upper is due to using reflection to get at the private field in your class. You can either use a block such as below to deal with the StyleCop and Resharper messages, which is easy to generate (from the Resharper SmartTag)
/// <summary>The xxx view model.</summary>
public class XXXViewModel : ReactiveObject
{
#pragma warning disable 0649
// ReSharper disable InconsistentNaming
[SuppressMessage("StyleCop.CSharp.NamingRules",
"SA1306:FieldNamesMustBeginWithLowerCaseLetter",
Justification = "Reviewed. ReactiveUI field.")]
private readonly bool _IsRunning;
[SuppressMessage("StyleCop.CSharp.NamingRules",
"SA1306:FieldNamesMustBeginWithLowerCaseLetter",
Justification = "Reviewed. ReactiveUI field.")]
private string _Name;
....
or change your properties from the full
/// <summary>Gets or sets a value indicating whether is selected.</summary>
public bool IsSelected
{
get { return _IsSelected; }
set { this.RaiseAndSetIfChanged(x => x.IsSelected, value); }
}
to its component parts such as
/// <summary>Gets or sets a value indicating whether is selected.</summary>
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
this.RaisePropertyChanging(x => x.IsSelected);
_isSelected = value;
this.RaisPropertyChanged(x=>x.IsSelected);
}
}
}
This pattern is also useful where you don't actually supply a "simple" property accessor, but may require a more derived variant where setting one value affects multiple others.
-2. Yes the documentation isn't ideal but I found that after Rx, picking up the RxUI samples was quite easy. I also note that the jumps from 2->4 seem to have all come with the changes to support Windows 8/Windows 8 Phone, and having picked up ReactiveUI for a Windows Store App then the DotNet 4.5 support is excellent. i.e. use of [CallerName] now means that you simply this.RaiseAndSetIFChanged(value) no need for the expression.
-3. I haven't any feedback on the logging side as I've not elected to use it.
-4. I've not mixed and matched with others frameworks either.
There's also a list of other contributors to ReactiveUI 4.2 at http://blog.paulbetts.org/index.php/2012/12/16/reactiveui-4-2-is-released/, including Phil Haack.

What are the Pros and Cons of having Multiple Inheritance?

What are the pros and cons of having multiple inheritance?
And why don't we have multiple inheritance in C#?
UPDATE
Ok so it is currently avoided because of the issue with clashes resolving which parent method is being called etc. Surely this is a problem for the programmer to resolve. Or maybe this could be resolve simularly as SQL where there is a conflict more information is required i.e. ID might need to become Sales.ID to resolve a conflict in the query.
Here is a good discussion on the pitfalls of multiple inheritance:
Why should I avoid multiple inheritance in C++?
Here is a discussion from the C# team on why they decided not to allow multiple inheritance:
http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85562.aspx
http://dotnetjunkies.com/WebLog/unknownreference/archive/2003/09/04/1401.aspx
It's just another tool in the toolbox. Sometimes, it is exactly the right tool. If it is, having to find a workaround because the language actually prohibits it is a pain and leads to good opportunities to screw it up.
Pros and cons can only be found for a concrete case. I guess that it's quite rare to actually fit a problem, but who are the language designers to decide how I am to tackle a specific problem?
I will give a pro here based on a C++ report-writer I've been converting to REALbasic (which has interfaces but only single-inheritance).
Multiple inheritance makes it easier to compose classes from small mixin base classes that implement functionality and have properties to remember state. When done right, you can get a lot of reuse of small code without having to copy-and-paste similar code to implement interfaces.
Fortunately, REALbasic has extends methods which are like the extension methods recently added to C# in C# 3.0. These help a bit with the problem, especially as they can be applied to arrays. I still ended up with some class hierarchies being deeper as a result of folding in what were previously multiply-inherited classes.
The main con is that if two classes have a method with the same name, the new subclass doesn't know which one to call.
In C# you can do a form of multiple inheritance by including instances of each parent object within the child.
class MyClass
{
private class1 : Class1;
private class2: Class2;
public MyClass
{
class1 = new Class1;
class2 = new Class2;
}
// Then, expose whatever functionality you need to from there.
}
When you inherit from something you are asserting that your class is of that (base) type in every way except that you may implement something slightly differently or add something to it, its actually extremely rare that your class is 2 things at once. Usually it just has behavour common to 2 or more things, and a better way to describe that generally is to have your class implement multiple interfaces. (or possibly encapsulation, depending on your circumstances)
It's one of those help-me-to-not-shoot-myself-in-the-foot quirks, much like in Java.
Although it is nice to extend fields and methods from multiple sources (imagine a Modern Mobile Phone, which inherits from MP3 Players, Cameras, Sat-Navs, and the humble Old School Mobile Phone), clashes cannot be resolved by the compiler alone.

Resources