CakePHP: How one Behavior use the Behavior function of a Plugin? - cakephp

I have two scenarios.
Scenario 1:
A ProcessableBehavior written in my APP/Model/Behavior needs to use a function inside another Behavior called Queryable in a Plugin.
How do I call Queryable.Queryable function doSomething from inside ProcessableBehavior?
Scenario 2:
If I write a Plugin Processable that now contains ProcessableBehavior and so this Behavior depends on Queryable.Queryable function doSomething, how do I do the calling?

Inside behaviors you can always invoke model methods. Since behaviors attached behave like those, you should be able to call them as they were part of the model.
// behavior 1
public function myFirstBehaviorMethod(Model $Model) {
// do sth
}
And
// behavior 2
public function mySecondBehaviorMethod(Model $Model) {
$Model->myFirstBehaviorMethod($foo, $bar);
}
The basic idea is that they don't necessarily have to know about it other. You just assume that they are part of the model (as behaviors enrich the functionality of models).
Note that you don't have to pass the $Model object, as it will internally use $Model.
Make sure you attach/load them in the right order.
If one depends on the other you could check on it in setup() etc:
// throw exception if not available
if (!$Model->Behaviors->attached('Queryable') {}

Related

Calling Apex method with multiple signatures from LWC

I've noticed some interesting behavior in an LWC that I am building and haven't been able to find much info on the cause. Basically I have an Apex method declared with multiple signatures:
// myMethod with 2 param signature
#AuraEnabled
public static void myMethod(String param1, String param2) {
// I expect this method to be invoked when called from the LWC code shown below
....
}
// myMethod with 3 param signature
#AuraEnabled
public static void myMethod(String param1, String param2, Boolean param3) {
// However this method gets invoked instead
....
}
When I attempt to call myMethod from an LWC, and only pass two parameters into the method, I would expect that the 2 param signature method would be invoked, however what happens is that the 3 param signature method is invoked, and the value of null is passed as the third params value.
runJob({param1, param2}).then(value => ... )
Is this expected behavior? When I call the methods through apex, the correct method is invoked by its signature, however this doesn't seem to be the case when calling the method from an LWC.
Is there a way for me to invoke the myMethod Apex method of the correct signature from an LWC?
Edit:
it will be banned at compile time in Summer'22 release. https://help.salesforce.com/s/articleView?id=release-notes.rn_apex_ValidationForAuraEnabledAnnotation.htm&type=5&release=238
Original:
It's worse than you think. runJob({param2, param1}) will work correctly too. "Correctly" meaning their names matter, not the position!
Your stuff is always passed as an object, not a list of parameters. You could have a helper Apex wrapper class and (assuming all fields are #AuraEnabled) it'll map them correctly. If you have list of parameters - well, a kind of unboxing and type matching happens even before your code is called. If you passed "abc" to a Date variable - a JSON deserialization error is thrown even before your code runs, you have no means to catch it.
https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex_wire_method
If the Apex method is overloaded, the choice of what method to call is
non-deterministic (effectively random), and the parameters passed may
cause errors now or in the future. Don't overload #AuraEnabled Apex
methods.
So... pick different names? Or funnel them so the 3-param version looks at the last param and calls 2-param one if needed and the business logic allows it. Generally - keep it simple, leave some comments and good unit tests or 2 months from now poor maintenance guy will struggle.
And (if you use the Apex PMD plugin and/or sfdx scanner) functions with long parameter lists are frowned upon anyway: https://pmd.github.io/latest/pmd_rules_apex_design.html#excessiveparameterlist
See also
https://github.com/trailheadapps/lwc-recipes/issues/196
https://salesforce.stackexchange.com/questions/359728/apex-method-overloading-is-not-working-when-called-from-lwc-javascript-controlle

uvm_object_utils_begin fails set field after test set filed

For some reason my object at the creation time does not pick configuration passed by test. I don't see GET when I enable tracing, only SET.
I have object as following:
class top_env_cfg extends uvm_object;
int set_default_env = 1;
`uvm_object_utils_begin(top_env_cfg)
`uvm_field_int(set_default_env,UVM_DEFAULT);
`uvm_object_utils_end
function new(string name = "top_env_cfg");
super.new(name);
endfunction
endclass
In my test, inside the build_phase I am doing the following:
uvm_config_db#(int)::set(this, "*", "set_default_env" ,0);
In my environment in build_phase I am creating this object as:
env_cfg = top_env_cfg::type_id::create("env_cfg", this);
After creating this object the set_default_env still 1.
What may be wrong, and how I can debug this.
Thanks in advance.
The important thing to understand about the "automated retrieval of config_db resources" is that it does not actually happen automatically. This Verilab paper explains what happens under the hood, and I am quoting the relevant section here:
[...] one question that is often asked with respect to retrieving data is:
do you always have to explicitly call the get() function? The short
answer is that it depends. In the UVM, there are mechanisms to
automate the retrieval of data from the configuration database. In
order to have the resource automatically retrieved two things must
happen:
First, that resource has to be registered with the factory using the field automation macros.
Second, super.build_phase(phase) must be called in the build_phase() function.
The "automated" retrieval will happen when you call super.build_phase() from a uvm_component. In the case that you are referring to in your question, you have a uvm_object (you don't have a UVM build_phase), so you would need to explicitly perform a uvm_config get() call in order to retrieve the resource from the database.

InvalidOperationException in Fsharp.Core.dll

So I am doing a simple personal project in winforms with F#. My code used to work, but now throws this exception for seemingly no reason.
An unhandled exception of type 'System.InvalidOperationException' occurred in FSharp.Core.dll
Additional information: The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.
The code is a member method that is being invoked from the constructor of the form itself
do
//lots of other constructor code before this point
// render the form
form.ResumeLayout(false)
form.PerformLayout()
form.ReloadGoals
//several other members before here
member form.ReloadGoals =
let x = 10 //crashes on this line
The website where I grabbed the template for the project I am using is this one.
Unfortunately I have made some substantial additions to this.
I would be glad to post more code, but I need to know what code would be relevant exactly, as I am not exactly sure and don't want to bog down the post in extraneous code.
Also I can't really find a lot of documentation on System.InvalidOperationException.
Every time I find it, it is being used as an example of an exception you can throw on your own, not what causes it.
See The F# 3.0 Language Specification (final version, PDF), ยง8.6.1 Primary Constructors in Classes:
During construction, no member on the type may be called before the last value or function definition in the type
has completed; such a call results in an InvalidOperationException.
Almost certainly, your code in the question doesn't tell the full story. If you hit the above
mentioned restriction, then there's somewhere an attempt to access a field or member not fully initialized.
Some example:
type X() as this =
let x = this.X
member __.X = 42
X()
One workaround might be to encapsulate the offending code in a member of its own and call that in the constructor instead. Another would be the wrapping in a function definition.
This will be an incomplete answer, since I cannot reproduce the problem (using F# interactive, the given example, the ReloadGoals modification, and Form.Show, the code runs fine). However, there are strange things happening:
Taken from the template, there should be a handler method for the Form.Load event, which fires when the type is fully constructed. Why is additional loading code in the constructor instead of this event handler? Load exists precisely to counter this kind of problem with unorderly initialization.
The template you are using isn't exactly sane F#. For example, initControls is a value of type unit that is evaluated where it is defined; its binding to a name is absolutely useless and should be replaced with a simple do. Writing initControls in the do block later has no effect at all. form.ResumeLayout(false); form.PerformLayout() should be equivalent to form.ResumeLayout(true), but I don't understand what these are doing in the constructor in the first place. The event handlers have two possibly unnecessary indirections: one to a delegate constructor, another to a method that has no real reason to exist -- the handlers should be lambdas or simple, private functions. Why are they public members?!
The error appearing in the question is probably caused by the usage of form in its own constructor. Move your new usage to the Load event handler, and it should work.
Personally, I would go further and ditch implementation inheritance by instantiating a plain Form and subscribing to its events. For example, in FSI, something similar to the template could be done like this:
open System.Drawing
open System.Windows.Forms
let form = new Form()
form.ClientSize <- new Size(600, 600)
form.Text <- "F# Form"
let formLabel = new Label()
formLabel.Text <- "Doubleclick test!"
formLabel.DoubleClick.Add <| fun _ -> form.Close()
form.Controls.Add(formLabel)
form.Show()
which uses no inheritance at all. (In an application, you'd use Application.Run etc instead of form.Show().) This does not run into initialization problems as easily and, additionally, is very useful if you want to encapsulate the form inside a simpler type or even just a function.

extjs function declaration syntax

In extjs, we often have syntax like this:
someFunction = function(){}
or:
someFunction : function(){}
What is the difference between the two? Also, what enables exts to use this syntax as opposed to the normal javascript syntax?
So far as i know, javascript syntax is like this:
function(){}//No '=' or ':'
There is not ExtJS function syntax. All these methods of defining a function are part of JavaScript and there is nothing new introduced by ExtJS. Lets take each case
function functionname() -
This is most common and is coming from the procedural programming school. Basically you are writing global functions and these are called by other functions in your script
Enter OOP in Javascript.. there is where the next two methods come in! Javascript is very flexible and extensible. Functions can be stored in variables, passed into other
functions as arguments, passed out of functions as return values, and constructed at run-time. You can also have anonymous functions! coming back...
someFunction = function() - In this case, you are storing a function in the variable 'comeFunction'.This variable can be part of an object or separate (But internally everything in javascript is object except for primitive data types).
someFunction : function() - In this case also, you are storing the function in the variable but this is during object declaration. You will see them used in ExtJS because it follows OOP.
You could also inject a method or modify the method you already specified by the above two methods. I hope this helps you understand more about functions.

method vs function vs procedure vs class?

I know the basics of this methods,procedures,function and classes but i always confuse to differentiate among those in contrast of Object oriented programming so please can any body tell me the difference among those with simple examples ?
A class, in current, conventional OOP, is a collection of data (member variables) bound together with the functions/procedures that work on that data (member functions or methods). The class has no relationship to the other three terms aside from the fact that it "contains" (more properly "is associated with") the latter.
The other three terms ... well, it depends.
A function is a collection of computing statements. So is a procedure. In some very anal retentive languages, though, a function returns a value and a procedure doesn't. In such languages procedures are generally used for their side effects (like I/O) while functions are used for calculations and tend to avoid side effects. (This is the usage I tend to favour. Yes, I am that anal retentive.)
Most languages are not that anal retentive, however, and as a result people will use the terms "function" and "procedure" interchangeably, preferring one to the other based on their background. (Modula-* programmers will tend to use "procedure" while C/C++/Java/whatever will tend to use "function", for example.)
A method is just jargon for a function (or procedure) bound to a class. Indeed not all OOP languages use the term "method". In a typical (but not universal!) implementation, methods have an implied first parameter (called things like this or self or the like) for accessing the containing class. This is not, as I said, universal. Some languages make that first parameter explicit (and thus allow to be named anything you'd like) while in still others there's no magic first parameter at all.
Edited to add this example:
The following untested and uncompiled C++-like code should show you what kind of things are involved.
class MyClass
{
int memberVariable;
void setMemberVariableProcedure(int v)
{
memberVariable = v;
}
int getMemberVariableFunction()
{
return memberVariable;
}
};
void plainOldProcedure(int stuff)
{
cout << stuff;
}
int plainOldFunction(int stuff)
{
return 2 * stuff;
}
In this code getMemberVariableProcedure and getMemberVariableFunction are both methods.
Procedures, function and methods are generally alike, they hold some processing statements.
The only differences I can think between these three and the places where they are used.
I mean 'method' are generally used to define functions inside a class, where several types of user access right like public, protected, private can be defined.
"Procedures", are also function but they generally represent a series of function which needs to be carried out, upon the completion of one function or parallely with another.
Classes are collection of related attributes and methods. Attributes define the the object of the class where as the methods are the action done by or done on the class.
Hope, this was helpful
Function, method and procedure are homogeneous and each of them is a subroutine that performs some calculations.
A subroutine is:
a method when used in Object-Oriented Programming (OOP). A method can return nothing (void) or something and/or it can change data outside of the subroutine or method.
a procedure when it does not return anything but it can change data outside of the subroutine, think of a SQL stored procedure. Not considering output parameters!
a function when it returns something (its calculated result) without changing data outside of the subroutine or function. This is the way how SQL functions work.
After all, they are all a piece of re-usable code that does something, e.g. return data, calculate or manipulate data.
There is no difference between of among.
Method : no return type like void
Function : which have return type

Resources