How to handle Zend Framework End User INI/Config settings - zend-framework

I have searched and searched for this but I think my terminology isn't correct as it keeps giving me the application settings for the zend site rather than an application settings for the End User.
I'd like to have a config.ini type file that the end user can edit values in. I'd like it to be ONLY the settings I wish them to see and to be able to create the value names as I think would make sense to them. So it would be something like
[General]
SiteName=MySite
ShowResources=TRUE
[Database]
Server=myServer
databasepath=mydbpath
...
So my two questions.
1. What is this type of file called because when I search application settinsg, I get the ZF application settings not one for an end user (presumably)
What is the best way to handle this type of file?
Thanks

In your bootstrap add:
protected function _initConfig()
{
$config = new Zend_Config_Ini(APPLICATION_PATH.'/configs/config.ini');
Zend_Registry::set('config', $config);
return $config;
}
replace config.ini with whatever you want the filename to be.
You can then access this config object anywhere in your application either as an application resource or through the registry (Zend_Registry::get('config')). So to get the SiteName from your example:
$config = Zend_Registry::get('config');
echo $config->General->SiteName;
For things like database settings, you'll want to access these in the bootstrap so you can use them to setup other resources. I would recommend you don't try and include database settings in your application.ini as well, instead manually setup the DB resource by adding another bootstrap method:
protected function _initDb()
{
$this->bootstrap('config');
$config = $this->getResource('config');
$db = Zend_Db::factory('Pdo_Mysql', array(
'host' => $config->Database->Server,
'username' => $config->Database->Username,
'password' => $config->Database->Password,
'dbname' => $config->Database->Dbname
));
return $db;
}
To explain this some more, $this->bootstrap('config'); ensures the config resource is loaded first. $this->getResource('config'); returns the config resource (the one created by the _initConfig() method). It then uses the data from this object to create the DB connection.

It's an INI file, which you can read and write via Zend_Config.
ZF has no concept of "user settings" -- users are defined by you, not by the framework.
Apps usually store user configs in a database, but that's totally up to you. You could store a directory of INI files instead. Either way, you have to do the implementation yourself.
Edit: Given that you have a ZF app that you're distributing to the customer, and they're only ever going to connect to one database with it, that changes things significantly. (I thought you originally meant that you'd have one instance of the app simultaneously connecting to multiple databases.)
In your case, I would use the standard ZF application/configs/application.ini file for your application's "internal" settings. Then, I'd have a separate local.ini (or whatever) in that same application/configs directory, which contains only those settings that you want the customer editing. Distribute a skeleton local.ini file with the app, that has instructions right in it, something like this:
; Remove the comment from this line.
;configured = 1
; You need to put your database credentials in here.
db_host = "PUT YOUR DATABASE SERVER NAME HERE"
db_user = "PUT YOUR DATABASE USERNAME HERE"
db_pass = "PUT YOUR DATABASE PASSWORD HERE"
Then just load the local.ini file via Zend_Config. I'd also add a check to your index controller's init method that checks to see if you're properly configured:
$localConfig = Zend_Registry::get('local_config'); // or wherever you put it
if (!$localConfig->configured) {
$this->_helper->redirector('config', 'error');
}
And then make a error/config view that says:
You didn't read the instructions. Go do that now.
Note there's nothing stopping the customer from editing anything they want, but this makes a logical separation and makes it harder to accidentally screw something up.

Related

How can I create and update pages dynamically in Sulu CMS?

I have the following situation:
A database stores information about houses (address, number of rooms, date built, last selling price, etc.)
This database is being manipulated through an app (let's call that app the "backend house app") that cannot be directly integrated in a Sulu-driven app. I can access the stored data through an API that gives me JSON-representations of House-objects. I can also have the app launch some sort of call to a Sulu-driven app when a house is created, updated or deleted.
The Sulu-driven app (let's call that the "frontend house app") with templates for "house", "room", etc., is connected to a different database on a different server. This Sulu-driven app's website-environment shows house-pages with room-pages where some content is pre-filled through a connection to the "backend house app". Other content only exists on the database of the "frontend house app", like user comments, appraisals of interior design, etc., according to configured aspects of the Sulu-templates.
What I want to achieve, is a way to automate the creation, updating and deletion of "frontend house app"-pages based on activity in the "backend house app".
For instance, when a new house is added in the "backend house app", I want it to notify the "frontend house app" so that the "frontend house app" will automatically create the entire node-tree for the newly added house. Meaning: a "house"-page with the required data filled in, "room"-pages for each room, etc., so that the content manager of the "frontend house app" can see the entire tree of the newly added house in the workspace and can start manipulating content in the already available templates. In addition to automatically creating these pages, I also want to pre-set the rights to update and create, since the content manager of the "frontend house app" must not be able to create new rooms or change the name of the house, for instance.
I did not manage to get it working, I'll just add what I already done to show where I got stuck.
I started out with the following code, in a controller that extends Sulu's own WebsiteController:
$documentManager = $this->get('sulu_document_manager.document_manager');
$nodeManager = $this->get('sulu_document_manager.node_manager');
$parentHousesDocument = $documentManager->find('/cmf/immo/routes/nl/huizen', 'nl');
$newHouseDocument = $documentManager->create('page');
// The backendApi just gives a House object with data from the backend
// In this case we get an existing House with id 1
$house = $backendApi->getHouseWithId(1);
$newHouseDocument->setTitle($house->getName()); // For instance 'Smurfhouse'
$newHouseDocument->setLocale('nl'); // Nl is the only locale we have
$newHouseDocument->setParent($parentHouseDocument); // A default page where all the houses are listed
$newHouseDocument->setStructureType('house'); // Since we have a house.xml template
// I need to grab the structure to fill it with values from the House object
$structure = $newHouseDocument->getStructure();
$structure->bind([
'title' => $house->getName(),
'houseId' => $house->getId(),
]);
$newHouseDocument->setWorkflowStage(WorkflowStage::PUBLISHED); // You would expect this to automatically publish the document, but apparently it doesn't... I took it from a test I reverse-engineered in trying to create a page, I have no clue what it is supposed to change.
$nodeManager->createPath('/cmf/immo/routes/nl/huizen/' . $house->getId());
$documentManager->persist(
$newHouseDocument,
'nl',
[
'path' => '/cmf/immo/contents/huizen/' . Slugifier::slugify($house->getName()), // Assume for argument's sake that the Slugifier just slugifies the name...
'auto_create' => true, // Took this value from a test that creates pages, don't know whether it is necessary
'load_ghost_content' => false, // Idem
]
);
$documentManager->flush();
Now, when I fire the controller action, I first get the exception
Property "url" in structure "house" is required but no value was given.
I tried to fix this by just manually binding the property 'url' with value '/huizen/' . $house->getId() to $structure, at the point where I bind the other values. But this doesn't fix it, as apparently the url value is overwritten somewhere in the persist event chain, and I haven't yet found where.
However, I can, just for testing purposes, manually override the url in the StructureSubscriber that handles the mapping for this particular persist event. If I do this, something gets created in the Sulu-app-database - hurray!
My phpcr_nodes table lists two extra records, one for the RouteDocument referring to /cmf/immo/routes/nl/huizen/1, and one for the PageDocument referring to /cmf/immo/contents/huizen/smurfhouse. Both have the workspace_name column filled with the value default_live. However, as long as there are not also records that are complete duplicates of these two records except with the value default in the workspace_name column, the pages will not appear in the Sulu admin CMS environment. Needless to say, they will also not appear on the public website proper.
Furthermore, when I let the DocumentManager in my controller action try to ->find my newly created document, I get a document of the class UnknownDocument. Hence, I cannot have the DocumentManager go ->publish on it; an Exception ensues. If I visit the pages in the Sulu admin environment, they are hence unpublished; once I publish them there, they can be found by the DocumentManager in the controller action - even if I later unpublish them. They are no longer UnknownDocument, for some reason. However, even if they can be found, I cannot have the DocumentManager go ->unpublish nor ->publish - that just has NO effect on the actual documents.
I was hoping there would be a Sulu cookbook-recipe or another piece of documentation that extensively describes how to create fully published pages dynamically, thus without going through the 'manual labor' of the actual CMS environment, but so far I haven't found one... All help is much appreciated :)
PS: For the purposes of being complete: we're running Sulu on a Windows server environment on PHP 7.1; dbase is PostgreSQL, Sulu being a local forked version of release tag 1.4.7 because I had to make some changes to the way Sulu handles uploaded files to get it to work on a Windows environment.
EDIT: a partial solution for making a new house page if none exists already (not explicitly using the AdminKernel, but should of course be run in a context where the AdminKernel is active):
public function getOrCreateHuisPagina(Huis $huis)
{
$parent = $this->documentManager->find('/cmf/immo/routes/nl/huizen', 'nl'); // This is indeed the route document for the "collector page" of all the houses, but this doesn't seem to give any problems (see below)
try {
$document = $this->documentManager->find('/cmf/immo/routes/nl/huizen/' . $huis->id(), 'nl'); // Here I'm checking whether the page already exists
} catch(DocumentNotFoundException $e) {
$document = $this->setupPublishedPage();
$document->setTitle($huis->naam());
$document->setStructureType('huis_detail');
$document->setResourceSegment('/huizen');
$document->setParent($parent);
$document->getStructure()->bind([
'title' => $huis->naam(), // Not sure if this is required seeing as I already set the title
'huis_id' => $huis->id(),
]);
$this->documentManager->persist(
$document,
'nl',
[
'parent_path' => '/cmf/immo/contents/huizen', // Explicit path to the content document of the parnt
]
);
}
$this->documentManager->publish($document, 'nl');
return $document;
}
First of all I think the following line does not load what you want it to load:
$parentHousesDocument = $documentManager->find('/cmf/immo/routes/nl/huizen', 'nl');
It loads the route instead of the page document, so it should look like the following:
$parentHousesDocument = $documentManager->find('/cmf/immo/contents/nl/huizen', 'nl');
Regarding your error with the URL, instead of overriding the StructureSubscriber you should simple use the setResourceSegment method of the document, which does exactly what you need :-)
And the default_live workspace is wrong, is it possible that you are running these commands on the website kernel? The thing is that the WebsiteKernel has the default_live workspace as default, and therefore writes the content in this workspace. If you run the command with the AdminKernel it should land in the default workspace, and you should be able to copy it into the default_live workspace with the publish method of the DocumentManager.
I hope that helps :-)

Zend_Session_SaveHandler_Interface and a session_id mysterie

I'm trying to setup my own Zend_Session_SaveHandler based on this code
http://blog.digitalstruct.com/2010/10/24/zend-framework-cache-backend-libmemcached-session-cache/
This works great, except that my session_id behave mysteriously.
I'm using the Zend_Session_SaveHandler_Cache class as you can find it in the blog above (except that I parked it in my own library, so it's name now starts with My_).
In my bootstrap I have:
protected function _initSession()
{
$session = $this->getPluginResource('session');
$session->init();
Zend_Session::getSaveHandler()->setCache( $this->_manager->getCache( 'memcached' ) );
}
To get my session going based on this code in my .ini file
resources.cachemanager.memcached.frontend.name = Core
resources.cachemanager.memcached.frontend.options.automatic_serialization = On
resources.cachemanager.memcached.backend.name = Libmemcached
resources.cachemanager.memcached.backend.options.servers.one.host = localhost
resources.cachemanager.memcached.backend.options.servers.one.port = 11213
So far so good. Until somebody tries to login and Zend_Session::rememberMe() is called. In the comments of Zend_Session one can read
normally "rememberMe()" represents a security context change, so
should use new session id
This of course is very true, and a new session id is generated. The users Zend_Auth data, after a successful log in, is written into this new session. I can see this because I added some logging functionality to the original class from the blog.
And here is where things go wrong. This new id isn't passed on the Zend_Session apparently, because Zend_Session keeps on reading the old id's session data. In other words, the one without the Zend_Auth instance. Hence, the user can no longer log in.
So the question is, how to make my saveHandler work with the new id after the regeneration?
Cheers for any help.
Ok, I'm blushing here....
I was looking at the wrong place to find this error. My session saveHandler was working just fine (so I can recommend Mike Willbanks his work if you want libmemcached session management).
What did go wrong then? Well, besides switching from file to libmemcached, I also switched from setting up my session in bootstrap to setting it up in my application.ini. So, instead of putting lines like
session.cookie_domain = mydomain.com
in my application.ini (which were then used in bootstrap as options to setup my session), I now, properly, wrote
resources.session.cookie_domain = mydomain.com
And this is were things went wrong, because.... I only changed those lines for production, I forgot to change them further down the ini file. In other words, my development env. got the cookie_domain of my production env., which is wrong as I use an other domain name during devolepment. So, on every page load, my cookie was invalidaded and a new session started. Mysterie solved...

Strange Zend_Session behaviour using Zend_Application

I'm writing to see if someone of you guys has encountered this problem before and have a chance to understand why it happened to me.
This is the story.
I developed many ZF applications before Zend Framework v. 1.8, then I've stopped for about 18 months. Now I had to start a new project on which I decided to use Zend Framework again.
On my local server I had the version 1.11.3 installed, so I didn't download the latest release.
Before the use of Zend_Application with the Bootstrap.php file I used to start sessions putting my session options in my config.ini file and then loading them into a Zend_Session instance like this:
config.ini
sessions.name = NAME
sessions.use_only_cookies = 1
sessions.save_path = APPLICATION_PATH "/../tmp/sessions"
sessions.strict = on
sessions.remember_me_seconds = 1800
index.php (into the public webserver directory) before starting the application:
Globals::startSession();
custom Globals class with various useful methods:
class Globals
{
static public function startSession()
{
$sessions_conf = self::getConfig()->sessions;
Zend_Session::setOptions($sessions_conf->toArray(););
Zend_Session::start();
}
}
This has always worked very well, enabling my sessions (used with Zend_Session_Namespace) and storing the session files in the save_path.
With Zend_Application the manual tells to simply store the session options in the application.ini file under the "section" resources and Zend_Session will be configured automatically...
I did it like this:
; SESSIONS
resources.session.name = NAME
resources.session.use_only_cookies = 1
resources.session.save_path = APPLICATION_PATH "/../tmp/sessions"
resources.session.strict = on
resources.session.remember_me_seconds = 1800
It didn't worked.
So I tried to use (not at the same time!) the _initSession() and _initForceSession() methods in the Bootstrap.php file, putting them at the beginning of the class and writing into them the code:
$this->bootstrap('session');
But session were never working, data were not stored between http requests and session files were never written into the save_path...
Could anyone, please, let me know if this is a normal behaviour (maybe I have missed something somewhere...)?
Obviously I solved the problem re-implementing my older method (and it works perfectly), but I would like to learn how to use it correctly.
Thanks in advance.
This should be a case of turn it on and it works, might have made it to easy.
I think you may have a problem with how you set your options in your application.ini:
; SESSIONS
resources.session.name = NAME
resources.session.name.use_only_cookies = 1
resources.session.name.save_path = APPLICATION_PATH "/../tmp/sessions"
resources.session.name.strict = on
resources.session.name.remember_me_seconds = 1800
according to the reference manual
To set a session configuration option, include the basename (the part
of the name after "session.") as a key of an array passed to
Zend_Session::setOptions().
with your options set correctly the bootstrap _initSession() should just work.
public function _initSession()
{
Zend_Session::start();
}
P.S. I use Zend_Session_Namespace all the time but rarely deal with a global session.
In your Bootstrap.php add
public function _initSession()
{
Zend_Session::start();
}
session options can be set in application.ini

Configuring form_path in Catalyst::Controller::Formbuilder

Using the Catalyst::Controller::FormBuilder module to handle forms in a Catalyst application.
The documentation says you can set the form_path like this:
form_path => File::Spec->catfile( $c->config->{home}, 'root', 'forms' ),
But the call to config() in my application is at the top level of the base module. Therefore, $c is undefined. So I can't call $c->config->{home}.
What is the proper way to configure form_path please?
You should be able to access configuration values that have already been set from your application's main module using the __PACKAGE__->config hash. Example: __PACKAGE__->config->{home} or __PACKAGE__->config->{'Controller::FormBuilder'}->{form_path}.
If you're trying to set the FormBuilder configuration in your applications main module, you should be able to use the code provided in the documentation and just replace $c->config->{home} with __PACKAGE__->config->{home}. I think they might have even made a mistake by not doing it this way, but I'm not sure.

Dynamically setting view directory

I am making a customer portal application using ZF. And the portal needs to work for different company brands. So I need to use all of the same backend code/controllers/etc, but dynamically change the view directory based off of the hostname.
Right now my view directory structure looks something like this:
/application/views/scripts/brand1/
/application/views/scripts/brand1/index/index.phtml
/application/views/scripts/brand1/error/error.phtml
/application/views/scripts/brand2/
/application/views/scripts/brand2/index/index.phtml
/application/views/scripts/brand2/error/error.phtml
/application/views/scripts/brand3/
/application/views/scripts/brand3/index/index.phtml
/application/views/scripts/brand3/error/error.phtml
and so on.
I am using the addScriptPath() function in bootstrap.php like so
protected function _initView()
{
$view = new Zend_View();
$view->doctype('XHTML1_STRICT');
$view->env = APPLICATION_ENV;
$view->addScriptPath(APPLICATION_PATH . '/views/scripts/brand1');
$view->addHelperPath(APPLICATION_PATH . '/views/helpers');
...
}
However when this is run, it is looking for all views using /views/scripts/brand1/(action).phtml instead of looking for views using the correct scheme /view/scripts/brand1/(controller)/(action).phtml
tl;dr is it possible to dynamically choose the view directory and have it work like the default /views/scripts/(controller)/(action).phtml behavior?
I knew I would find the answer after I posted here. In case anyone else encounters the same problem, the solution was using:
$view->setBasePath(APPLICATION_PATH . '/views/brand1');
And then modifying the directory structure to:
/application/views/brand1/scripts/...