I was going through Form Creation in ZF2 and I read the following statement.
"
You can create the entire form, and input filter, using the Factory. This is particularly nice if you want to store your forms as pure configuration; you can simply pass the configuration to the factory and be done."
Can anybody tell in detail what does PURE CONFIGURATION mean?
It means that you're able to store your forms within any config file, e.g. module.config.php and then pass this configuration key into the form factory. This is similar what has been done in ZF1 often times, too.
This whole process is done through the Zend\Form\Factory and if you check out the source code you'll see that you could pass it the following array to create a Form
$someConfig = array(
'form-key-name' => array(
'fieldsets' => array(
'fieldset_1' => array(
'elements' => array(
'elem_x' => array(/** Single Form-Element Array*/)
),
'fieldsets' => array(
'fs_y' => array(/** More Sub-Fieldset Array*/)
),
)
)
)
);
Note that this example is quite incomplete (missing name => foo), hydrator configuration, inputFilter configuration, etc... but as it is this should give you a idea of what's meant by that statement.
Using the above-mentioned configuration then you can pass it to the factory
$factory = new \Zend\Form\Factory();
$form = $factory->createForm($someConfig['form-key-name']);
Related
I am creating search application using elasticsearch. I want to make indexing with zero downtime. I found one solution using aliases with client library in php. But I don't know how to implement it using client library in php.
In order to add an alias to an existing index, you need to call the updateAliases method:
$params['body'] = array(
'actions' => array(
array(
'add' => array(
'index' => 'your_index',
'alias' => 'your_alias'
)
)
)
);
$client->indices()->updateAliases($params);
If you are looking for a more complete solution, have a look at http://elasticorn.net - you can configure your index via yaml and it automatically creates them with aliases and the possibility to remap / reconfigure indices on the fly.
I give. Been searching and trying different stuff for hours.
Using Cakephp 2.3.5.
I'll get straight to it.
I want to use a session variable in my Category model, but it doesn't like it when I try any of the following...
$this->Session->read('market_id')
CakeSession::read('market_id')
SessionHelper::read('market_id')
Here is the model snippet where I'm trying to use it...
public $hasAndBelongsToMany = array(
'Vendor' => array(
'className' => 'Vendor',
'joinTable' => 'categories_vendors',
'foreignKey' => 'category_id',
'associationForeignKey' => 'vendor_id',
'unique' => 'keepExisting',
'conditions' => array( 'market_id' => ???? )
)
);
I'm stuck like a wheelbarrow in the mud. I've read countless opinions of why I shouldn't use session data in the model, but this makes perfect sense to me since it will never be called without this value set, and it should never return anything other than the vendors with that market_id. But that value does change.
I'm completely guilty of doing everything I can to avoid messing with my models. The whole skinny controller idea... yea... nice thought, but I just haven't figured it out yet. And so it goes. The first time I try to modify a model... I can't figure out how.
I've read countless opinions of why I shouldn't use session data in the model
That's correct. It will cause tight coupling as well and make it harder to test. And it's not only valid for models but everything. Don't create tight coupled code.
It is better to pass data and objects around. For example:
// Model Method
public function getSomething($someSessionValue) { /*...*/ }
// Controller
$this->SomeModel->getSomething($this->Session->read('something'));
If you need your data in a lot methods you can set it:
public function setSomeModelProperty($value) {
$this->_someProperty = value; // _ because it should be protected, the _ is the convention for that in CakePHP
}
However, I personally would very like go for passing the data to each method. But it depends on the whole scenario.
And you can't do this any way because it will cause a syntax error. You can't use variables or properties in the property declaration.
'conditions' => array( 'market_id' => ???? )
So bind it later by a method like
public function bindVendors($marketId) {
$this->bindModel(/*...*/);
}
when needed.
Or even better, simply use the conditions only when needed and declare them in your find options:
[
'contain' => [
'Vendor' => [
'conditions' => /* conditions here */
]
]
]
I am new to PHP and I have a lots of forms in PHP. The forms make use of the standard HTML Input fields and need to be validated on the serverside. How can I implement this, so that I do not have to write lots of boilerplate HTML over and over again, rather only write the minimal amount of code that generate the "full forms". What is the recommended approach to implement this? Thanks.
If you prefer to do it all yourself, you should at least do it PHP-Classes which will save you from re-writing (if done right ;-)). Handle attributes of the fields through an assoc array, e.g. like this:
<?php
$form = new Form("MyInput", array ("submit" => "myform.php") );
$form->AddField("input_text", array ("label" => "Your name") );
?>
To handle validation, you could use attributes such as
$form->AddField("input_text", array (
"label" => "Your name" ,
"validate" => "required"
) );
(Only examples, there's a lot of code releated to this which you'd need to write once...)
That should be useful for learning purposes...
Next, you could use JS to validate. Pls. note that JS does client-side validation only and you cannot rely on it being executed (user might have turned of JS in his browser), so you still MUST validate in PHP when receiving the data. (And you could use JS-Libraries for that - I've used Parsley and was quite happy with it...)
If you want to skip that experience, use Frameworks or Templating Engines.
I would suggest to create a form template. Consider using a method (of class View):
private static function capture($view_filename, array $view_data)
{
extract($view_data, EXTR_SKIP);
ob_start();
require $view_filename;
return ob_get_clean();
}
And call the static function capture (caution: consider using of __toString() to print objects) Pseudo-code:
echo View::capture('template', array('id' => '1', 'class' => 'userForm', 'inputs' => array(0 => array('label' => 'Name', 'type' => 'text'), 1 => array('label' => 'Password', 'type' => 'password')));
My goal is to have configuration settings shared and editable within each module in a Zend Framework 2 project. After research, I came to this: http://akrabat.com/zend-framework-2/injecting-configuration-into-a-zf2-controller/ which worked great at first but after my application keeps expanding to more modules and more controllers, I don't appreciate this solution. Precisely, I don't appreciate having to "implement" interface, add SetConfig method and so on. Instead, I'd like to be able to just call on $GLOBALS or similar in my controller and get the parameter of interest.
Say I have a file config.local.php with the following format:
return array(
'group1' => array(
'key1' => 'value1',
'key2' => 'value2',
)
'group2' => array (
'subgroup' => array (
'keyA' => 'valueA',
'keyB' => 'valueB',
),
)
);
Right now, i'm following the tutorial above and after implemeting the ConfigAwareInterface in my controller, I get valueA using
$this->config['group2']['subgroup']['keyA']
I'm now hoping to just rather call $GLOBALS['group2']['subgroup']['keyA'] without the ConfigAwareInterface intermediate.
I laid the following quick pseudo code to help me achieve that:
for every this->config as key => value
if $key is not array
$GLOBALS[$key] => $value
else
for every $value as $k => $v
$GLOBALS[$key][$k] => $value
As ZF2 and php are new to me, I'm not completely sure I can have more than 1 index/nested keys for $GLOBALS but I can tailor my config file to avoid that.
There are probably other logical mistakes above. But just to get the point. Now, is this the best way to go about global configuration or is there a better approach?
Thanks in advance.
You can always easily access the configuration via:
$this->getServiceLocator()->get('config');
What Akrabat did was to provide a shortHand getConfig()-
I just read the Rob Allen's akrabat ZF2 tutorial (http://akrabat.com/wp-content/uploads/Getting-Started-with-Zend-Framework-2.pdf) on how to inject dependencies into your stuff like, injecting in your table adapter into your table classes.
This seems to be how I'm supposed to do it:
array(
'Application\Model\DbTable\UserTable',
) => array(
'parameters' => array(
'config' => 'Zend\Db\Adapter\PdoMysql',
)
),
array(
'Application\Model\DbTable\UserProfileTable',
) => array(
'parameters' => array(
'config' => 'Zend\Db\Adapter\PdoMysql',
)
),
Ok that's pretty cool but I've got around 84 tables so am I going to have to add each of these and say that I want PdoMySQL injecting into them all. Is there any proper way to do this such as specifying my entire DbTable folder? Not even this works:
array(
'Application\Model\DbTable\UserTable',
'Application\Model\DbTable\UserProfileTable'
) => array(
'parameters' => array(
'config' => 'Zend\Db\Adapter\PdoMysql',
)
),
Anyone else doing this and found a better solution?
Thanks, Dom
Your question is a good one, and I agree, this a scenario where dependency injection does NOT make sense. I haven't browsed the ZF2 API yet, did they completely abandon the ability to bind adapter at the connection level, rather than the table level?
In my database class I use a yaml file to store connection settings; username, password, adapter, etc. I did it in a format which can be passed straight to Zend_Config, which can then be passed to the Zend_Db class.
// Entry in connection.yml
database:
adapter: Pdo_Mysql
params:
host: myhost
dbname: mydatabase
username: myusername
password: mypassword
// Parse yaml file to get above snippet in an array ($dbConnectionparams)
$config = new Zend_Config($dbConnectionParams);
$dbo = Zend_Db::factory($config->database);
Now, If I ever need to change the adapter for a database connection I only need to change it in one location, the connection.yml file.
Also, I believe you can store this type of connection data in various other formats (xml, etc).
You should implement Zend\Db\Adapter\AdapterAwareInterface in your model classes and request them via service manager in your controllers. Take a look at my blog post for more details: http://cmyker.blogspot.com/2012/11/zend-framework-2-model-database-adapter.html