Error : Call to a member function build() on null in cakephp 3 - helper

I need to use session in my MhtmlHelper.
namespace App\View\Helper;
use Cake\View\Helper;
use Cake\View\Helper\HtmlHelper;
class MhtmlHelper extends HtmlHelper {
}
When I add this line,
public $helpers = ['Session'];
in my helper, this error appears.
Error: Call to a member function build() on null
File D:\xampp\htdocs\projects\bookmarker\vendor\cakephp\cakephp\src\View\Helper\HtmlHelper.php
Line: 323

You need to include all helpers that the HtmlHelper need to work:
https://github.com/cakephp/cakephp/blob/master/src/View/Helper/HtmlHelper.php#L40
You can append to that list as many helpers as you may need for your task.

Related

Is it possible to use the Slugger interface other than in a constructor?

I'm looking to use the sluggerInterface in a class. But I want to keep:
public function __construct()
{
}
So I want to use sluggerInterface in my class without adding any argument in my constructor. (this is in order to automatically create 1 slug when creating an object).
So I want a code different from this one:
use Symfony\Component\String\Slugger\SluggerInterface;
class MyService
{
private $slugger;
public function __construct(SluggerInterface $slugger)
{
$this->slugger = $slugger;
}
public function someMethod()
{
$slug = $this->slugger->slug('...');
}
}
Thank you !
You do not want to use autowiring in your constructor ?
You could just create a new slugger, for example with Symfony\Component\String\Slugger\AsciiSlugger;
$slugger = new AsciiSlugger();
$slugger->slug('Please slug this.')->toString();
Or you could also use autowiring with another method using #required annotation (or attribute #[Required] for PHP 8+)
private $slugger;
#[Required]
public function setSlugger(SluggerInterface $slugger): void
{
$this->slugger= $slugger;
}
this is in order to automatically create 1 slug when creating an object
You may also want to look into event listener, using doctrine event prePersist to slug your entity when persisted could be another idea.
Finally, gedmo doctrine-extensions sluggable may interest you as well.

How to Stop static initialization with PowerMockito

I am working on an API for work, we use a shared library for multiple projects for the purposing of our logging framework. The class used uses all static methods for its calls.
I am trying to Unit test an API call, I can not have it call anything on the Logging class, else it will fail.
I have tried using Powermock, but it fails on
PowerMockito.mockStatic(LoggingFramework.class);
Mockito.when(LoggingFramework.startACall(anyString())).thenReturn("someTimestamp");
returning a
ClassCastException: org.apache.logging.slf4j.SLF4JLoggerContext cannot be cast to org.apache.logging.log4j.core.LoggerContext
the line in LoggingFramework that throws it, is inside a static initializer block outside of any methods in the class.
In order to suppress static initialization you should use #SuppressStaticInitializationFor. So your code will look like this:
#RunWith(PowerMockRunner.class)
#SuppressStaticInitializationFor("so.LoggingFramework") //here goes fully-qualified name of a class
public class LoggingFrameworkTest {
#Test
public void test() {
//given:
PowerMockito.mockStatic(LoggingFramework.class);
Mockito.when(LoggingFramework.foo(anyString())).thenReturn("stub");
//when:
String foo = LoggingFramework.foo("ignored");
//then:
PowerMockito.verifyStatic(LoggingFramework.class, Mockito.times(1));
LoggingFramework.foo(anyString()); //two-step verification of a static method
assertThat(foo, equalTo("stub"));
}
}
Verification of a static method is performed in two steps. It is explained here

Why doesn't a Groovy closure have access to injected class member?

We are using Groovy and Guice on a project and I came across the following error:
groovy.lang.MissingPropertyException: No such property: myService for class: com.me.api.services.SomeService$$EnhancerByGuice$$536bdaec
Took a bit to figure out, but it was because I was referencing a private class member, that was injected, inside of a closure. Can anyone shed any light as to why this happens?
Furthermore, is there any better way of doing this?
Here is a snippet of what the class looks like:
import javax.inject.Inject
import javax.inject.Singleton
#Singleton
class MyService extends BaseService<Thing> {
#Inject
private ThingDao thingDao
#Inject
private OtherService<Thing> otherService
#Override
List<Thing> findAll() {
List<Thing> things = this.dao.findAll()
things.each {
//Note: This doesn't work!
otherService.doSomething()
}
things
}
I either have to use a standard for loop or not use the injected member which then tends to lead to code duplication.
TLDR;
Either declare otherService public (remove private modifier) or add a getter OtherService<Thing> getOtherService(){otherService}
If you absolutely want to avoid exposing the field through a property, you can do the following trick: create a local variable outside the Closure scope that references your service:
OtherService<Thing> otherService=this.otherService
things.each {
//Note: This will work! Because now there is a local variable in the scope.
//This is handled by normal anonymous inner class mechanisms in the JVM.
otherService.doSomething()
}
Explanation
Under the hood, your closure is an object of an anonymous class, not the object that has your private field, otherService.
This means that it can't resolve a direct reference to the field. Accessing a symbol inside the closure will first look at local variables, and if no match is found, the getProperty() method in Closure will be called to find a property, depending on the resolution strategy that you defined. By default, this is OWNER_FIRST.
If you look the code of Closure#getProperty:
switch(resolveStrategy) {
case DELEGATE_FIRST:
return getPropertyDelegateFirst(property);
case DELEGATE_ONLY:
return InvokerHelper.getProperty(this.delegate, property);
case OWNER_ONLY:
return InvokerHelper.getProperty(this.owner, property);
case TO_SELF:
return super.getProperty(property);
default:
return getPropertyOwnerFirst(property);
}
You see that the owner, delegate and declaring objects need to have matching properties.
In groovy, if you declare a field private, you won't get auto-generated accessor methods, so no properties will be publicly exposed for outside objects.

Class name class variable = null - what does this line mean in Android?

I am having trouble understanding the meaning of the following code:
public class CustomListViewAndroidExample extends Activity {
ListView list;
CustomAdapter adapter;
public CustomListViewAndroidExample CustomListView = null; // What does this line mean?
public ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
Its instance of current activity you can use in oncreate like
CustomListView.addContentView(view, params);
It's just like an "ordinary" variable except that it's explicitly set to null when the class is created. It's no different in principal than the following line:
CustomListViewValuesArr = new ArrayList<ListModel>();
This isn't really any different than setting the value in the constructor or OnCreate method.
Note that, as with your other variables, you'll need to initialize this to something other than null in order to be able to use it.
It is slightly odd that it's public, though. I'd also recommend including explicit access modifiers in front of your other fields - it's a bad practice to omit them and rely on the defaults.

Calling Method of class within it

// What is the technical reason behind this scenarios..?
You're trying to use a statement other than a declaration directly inside the class - rather than within a method. When did you expect the method to get called?
Basically all you can have directly within a type is a bunch of declarations - methods, variables, constructors, events, nested types etc. Method calls (or any other statements) which aren't part of a declaration have to be written within methods, constructors etc.
Method call statement can not be part of a class declaration, but only within Function members declarations scope, such as Methods, Properties, Constructors etc.
For example:
public class ExampleClass
{
private void SayHelloWorld()
{
Console.Writeline("Hello World!");
}
public void CallSayHelloWorldMethod()
{
this.SayHelloWorld();
}
}
At the above example you can see that I call the SayHelloWorld method within the CallSayHelloWorldMethod metod.
Update:
The closest thing I can think of in your case is to use the class's constructor where your method call will be executed as soon as you'll instantiate your class:
public class ExampleClass
{
//The class constructor
public ExampleClass()
{
this.SayHelloWorld();
}
private void SayHelloWorld()
{
Console.Writeline("Hello World!");
}
}
And when you instantiating it, it will be immediately called:
//Your method call will be executed here
ExampleClass exampleClass = new ExampleClass();
You have a few problems... This won't even compile as you are trying to call the method obj.m1() in the class definition.
A obj = new A();
obj.m1(); // Why this code wont work??? --> This must be inside a method
When you create an instance of a class it will create a new member variable called obj which is an instance of A --> A obj = newA() above;
You will now be able to call obj's methods as in your second example.
Also, in order to get this to compile you will need to fix the m2 method:
public void m2() { //--> should have a curly brace
obj.m1(); // But This will work.
}

Resources