namespace in php - php-5.3

<?php
namespace foo;
use My\Full\Classname as Another;
// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;
// importing a global class
use ArrayObject;
$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use ArrayObject" we would instantiate an object of class foo\ArrayObject
?>
Please help me with this.
What is the meaning of use My\Full\Classname as Another;

Thats an alias. Every time you refer Another as a (relative) namespace, or classname, it gets resolved to \My\Full\Classname
$x = new Another;
echo get_class($x); // "\My\Full\Classname"
$y = new Another\Something;
echo get_class($y); // "\My\Full\Classname\Something"
Identifiers starting with a namespace separator \ are full-qualified names. If it's missing, the identifiers are resolved against the current namespace and against the alias definitions defined by use (in this order) (except for identifiers in use and namespace: They are always full-qualified).
PHP-Manual: Namespaces

Related

How to implement dependency injection in Flutter manually?

Since there is no official library from the flutter team, I'm trying to implement the dependency injection in flutter manually using the singleton pattern, after a long search this is what I came up with:
class Injector{
Injector._internal();
static final _singleton = new Injector._internal();
factory Injector() => _singleton;
SomeClass get someClass => new SomeClass();
}
Now, Injector is singleton that has one instance once instantiated and SomeClass is the dependency I want to inject in my code. The above code works, but the problem is where should I instantiate the Injector class and make it available every where in my code. Do you think Global Variable is good in this situation or is there a better way? Thanks.
To implement your own dependency injection I usually use a combination of
A 'Bindings' class which has getters to all injected services
A static getter/setter which holds a single instances of the Bindings class. This is important for overriding the bindings.
The getters which return classes should lazily construct them if they have dependencies. This allows you to override any parts of your graph by extending the Bindings class and setting it in the global bindings. For example, below I have three classes with the third depending on the first two.
class Foo {}
class Bar {}
class Fizz {
Fizz(this.foo, this.bar);
final Foo foo;
final Bar bar;
}
class Bindings {
/// Can be final since there are no dependencies
final Foo foo = new Foo();
final Bar bar = new Bar();
Fizz _fizz;
Fizz get fizz {
_fizz ??= new Fizz(foo, bar);
return _fizz;
}
}
Bindings get bindings => _bindings;
Bindings _bindings;
set bindings(Bindings value) {
_bindings = value;
}
Now suppose I want to override Foo for testing. I can extend the Bindings class and override the field/getter that returns Foo. and in my test setup, I set bindings with this new instance. Now when Fizz is created, the MockFoo instance is used instead of Foo
class MockFoo implements Foo {}
class BindingsOverride extends Bindings {
#override
final Foo foo = new MockFoo();
}
void main() {
bindings = new BindingsOverride();
}
Edit: In an earlier version I was using a static class. I don't think you need to refer to foo and bar through the bindings instance, you can just refer to the members directly.
This is my solution for this problem. First I created a dart file named injector.dart with this code:
// the singleton is private to this package
final _injector = new _Injector();
// expose depedencies
final foo = _injector.foo;
final bar = _injector.bar;
class _Injector{
// create a singleton
_Injector._internal();
static final _singleton = new _Injector._internal();
factory _Injector() {
return _singleton;
}
// the dependecies
Foo get foo => new Foo();
Bar get bar => new Bar();
}
This is how the code work, first we create a singleton class _Injector that creates needed dependencies and then exposes these dependencies with top-level variables. This way the dependencies are accessible anywhere the injector.dart package is accessible.
What do you think guys? is this good or is there a better implementation? Thanks

Zend Framework 2 - How to give declare folder path in terms of "use" and "namespace"

I am facing problem while creating adapter object in controller file named Listcontroller.My code is
namespace Blog\Controller;
use Blog\Service\PostServiceInterface;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Db\Sql\Sql;
use Zend\Db\Adapter\Adapter;
class ListController extends AbstractActionController
{
/**
* #var \Blog\Service\PostServiceInterface
*/
protected $postService;
public function __construct(PostServiceInterface $postService)
{
$this->postService = $postService;
}
public function indexAction()
{
$adapter = new Zend\Db\Adapter\Adapter($configArray);
print_r($adapter);
//code ....
}
}
here it is serching to find Zend\Db\Adapter\Adapter inside Blog\Controller.
Error is -> Fatal error: Class 'Blog\Controller\Zend\Db\Adapter\Adapter' not found. Can anybody tell me please how can i move two folder back from above path. so that i can get proper object??
You don't need the fully qualified class name (FQCN) when instantiating a new Adapter since you declare that class path via use statement:
use Zend\Db\Adapter\Adapter;
Change this block
public function indexAction()
{
$adapter = new Zend\Db\Adapter\Adapter($configArray);
print_r($adapter);
}
to
public function indexAction()
{
$adapter = new Adapter($configArray);
print_r($adapter);
}
It should work.
Anyway, new \Zend\Db\Adapter\Adapter($configArray) also works (notice the first backslash) but its longer, harder to type and less readable than first example.
You may also want to read namespace aliasing/importing section of the documentation.

how to add form validation from controller in zend framework 2

I tried to add a validation from my controller like below. but it always shows this
if ($request->getPost('ownerType') == "Company") {
$form->getInputFilter()->get('companyName')->getValidatorChain()->addValidator('required');
}
shows error. I confused with below error.
Catchable fatal error: Argument 1 passed to Zend\Validator\ValidatorChain::addValidator() must implement interface Zend\Validator\ValidatorInterface, string given, called in E:\xampp\htdocs\hossbrag\module\WebApp\src\WebApp\Controller\JobController.php on line 177 and defined in E:\xampp\htdocs\hossbrag\vendor\zendframework\zendframework\library\Zend\Validator\ValidatorChain.php on line 100
My controller is here
<?php
namespace WebApp\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use WebApp\Entity\User;
use Zend\View\Model\JsonModel;
use vendor\mpdf\mpdf;
class JobController extends AuthenticatedController
{
public function createAction()
{
$form = new \WebApp\Form\JobpostingForm();
$form->get('companyName')->setValueOptions($company);
$checkAgreement = true;
$request = $this->getRequest();
if ($request->getPost('ownerType') == "Company") {
$form->getInputFilter()->get('companyName')->getValidatorChain()->addValidator('required');
}
}
}
What should to change in my controller to get appropriate solution.
If you encounter such a clear error, simply check out the sources ;)
First one to check would be Zend\Validator\ValidatorInterface. The Error shows you, that a Class implementing this interface is excepted. Looking at the code you'll see, the function wants a Class, not just a string.
But since you're used to ZF a little it becomes clear that you know there's other ways to add stuff. So let's take a look at Zend\InputFilter\InputFilter#add(). You'll see that the first param of the add() function indeed asks for a class implementing ValidatorInterface. But it also accepts some other stuff:
/**
* Add an input to the input filter
*
* #param array|Traversable|InputInterface|InputFilterInterface $input
* #param null|string $name
* #return InputFilter
*/
public function add($input, $name = null)
{
//...
}
It also accepts array, Traversable, InputInterface and InputFilterInterface. So choices are there.
Now, i have never done this myself and i sincerely hope this works (if not i suck!), but assuming you're using the array-syntax, all you have to do is this:
[...]->getValidatorChain()->add(array(
'type' => 'Zend\Validator\NotEmpty'
));
Let me know if this worked out for you ;)

ZF2: How to attach listener on the event in the Module class?

I want to set a basePath to be the same for every component of my Mvc for a given request. I mean when I call these methods I want to get the same result, lets say '/spam/ham/':
echo $this->headLink()->prependStylesheet($this->basePath() . '/styles.css') // $this->basePath() has to be '/spam/ham/'
$this->getServiceLocator()
->get('viewhelpermanager')
->get('headLink')
->rependStylesheet($this->getRequest()->getBasePath() . '/styles.css') // $this->setRequest()->getBasePath() has to be /spam/ham/
How to set the basePath for the first case I have found already, here's my question. By the way, the original manual doesn't have any info I received from the answer.
And now the second one - the basePath has to be set in the Request:
$this->getRequest()->getBasePath()
Here I found some answer that in fact doesn't work at all http://zend-framework-community.634137.n4.nabble.com/Setting-the-base-url-in-ZF2-MVC-td3946284.html. As said here StaticEventManager is deprecated so I changed it with SharedEventManager :
// In my Application\Module.php
namespace Application;
use Zend\EventManager\SharedEventManager
class Module {
public function init() {
$events = new SharedEventManager();
$events->attach('bootstrap', 'bootstrap', array($this, 'registerBasePath'));
}
public function registerBasePath($e) {
$modules = $e->getParam('modules');
$config = $modules->getMergedConfig();
$app = $e->getParam('application');
$request = $app->getRequest();
$request->setBasePath($config->base_path);
}
}
}
And in my modules/Application/configs/module.config.php I add:
'base_path' => '/spam/ham/'
But it desn't work. The problems are:
1) The run never comes to the registerBasePath function. But it has to. I've attached an event with the listener in the init function.
2) When I change SharedEventManager for just EventManager it happens to come to the registerBasePath function but an exeption is thrown:
Fatal error: Call to undefined method Zend\EventManager\EventManager::getParam()
What do I do wrong? Why the run of the program doesn't come to the registerBasePath function? If this is the only way to set the basePath globally then how to do it right?
I know the documentation is lacking of these kinds of things. But you are right in the way to approach this:
Be early (so at bootstrap)
Grab the request from the application
Set the base path in the request
The docs are lacking this information and the post you refer to is quite old. The fastest and easiest way to do this is using the onBootstrap() method:
namespace MyModule;
class Module
{
public function onBootstrap($e)
{
$app = $e->getApplication();
$app->getRequest()->setBasePath('/foo/bar');
}
}
If you want to grab the base path from your config, you can load the service manager there:
namespace MyModule;
class Module
{
public function onBootstrap($e)
{
$app = $e->getApplication();
$sm = $app->getServiceManager();
$config = $sm->get('config');
$path = $config->base_path;
$app->getRequest()->setBasePath($path);
}
}

Grails: why would this service class be null?

Given this grossly simplified rendition of the setup:
package net.myexample.plugin
class MyExampleService {
Map doMunge(Map m) {
// do stuff to 'm'
return m
}
}
/****************************** BREAK: NEXT FILE ******************************/
package net.myexample.plugin
class MyTagLib {
static namespace = 'p'
def myExampleService
def tag = { attrs, body ->
def m = doMungeAndFilter(attrs.remove('m'))
out << g.render(template: '/template', plugin: 'my-example-plugin', model: m)
}
Map doMungeAndFilter(def m) {
def mm = myExampleService.doMunge(m)
// do stuff to 'm'
return mm
}
}
/****************************** BREAK: NEXT FILE ******************************/
package net.myexample.app
import net.myexample.plugin.MyExampleService
class MyExampleService extends net.myexample.plugin.MyExampleService {
def doMunge(def m) {
def mm = super.doMunge(m)
// do more stuff to 'mm'
return mm
}
}
/****************************** BREAK: NEXT FILE ******************************/
package net.myexample.app
import net.myexample.plugin.MyTagLib
class MyTagLib extends net.myexample.plugin.MyTagLib {
static namespace = 'a'
def myExampleService
def tag = { attrs, body ->
def m = doMungeAndFilter(attrs.remove('m'))
out << g.render(template: '/template', plugin: 'my-example-plugin', model: m)
}
Map doMungeAndFilter(def m) {
def mm = super.doMungeAndFilter(m)
// do more stuff to 'mm'
return mm
}
}
/**
* But we get an exception that cites that it cannot call 'doMunge' on a null
* object -- which could only be 'myExampleService'
*/
Why would the service appear to be null when the method on the app's taglib calls its superclass (the taglib on the plugin), which in turn calls the method on the service?
The best theory I could come up with is that the service is not actually being instantiated in the app's taglib class because there are no explicit references to it aside from the def. I presume that this is the case because if I move all the logic from service class's method into the taglib's method, it works as expected.
(For the sake of painting a complete picture: MyExampleService.doMunge is called in other places, whereas the subsequent filtering (in MyTagLib.doMungeAndFilter) is only needed for the taglib.)
Alternatively: if I move doMungeAndFilter into another service class, creating the base version in the plugin and extending it in the app, that works fine. Which I suppose is an acceptable conclusion, though it feels like bloat to create another service class just to support the taglib like that.
Thoughts? Tips? Glaring errors or omissions?
Remove the def myExampleService from the subclass taglib. A property like that in Groovy compiles to a private field plus a public getter and setter, so in the superclass taglib you have implicitly
private Object myExampleService;
public void setMyExampleService(Object svc) {
this.myExampleService = svc;
}
// getter similar
When you declare myExampleService again in the subclass the subclass gets its own private field (with the same name) and the setter gets overridden to store the supplied value in this subclass field instead of the superclass one. Spring calls the setter to inject the service, so the end result is that the superclass private myExampleService never gets set, hence the null pointer exception when trying to call myExampleService.doMunge in the superclass.
The subclass has access to the superclass property via the inherited getter and setter so it doesn't need to re-declare it.
This is just a quick guess, but is you taglib class file located under /grails-app/taglib, or somewhere in your /src directory? I've noticed I can't get services to inject (automatically, at least) into classes located outside the /grails-app folder.

Resources