I started using this module from Zend (https://framework.zend.com/manual/2.3/en/modules/zend.ldap.introduction.html) for work with LDAP, and I want to implement it into my classes which works with LDAP. But when I want to use some php ldap function which are not implemented in Zend-Ldap I have to get the resource identifier but I always get resource(37) of type (Unknown) or error dap_mod_del(): 41 is not a valid ldap link resource (2). I think I use Zend module correctly you can see below.
Other zend-ldap features work perfect. But I cant get the right resources.
index.php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/api/AtaLdap.php';
require_once __DIR__ . '/api/classes/Users.php';
$ldap = new AtaLdap\AtaLdap();
var_dump($ldap->Zend());
AtaLdap.php
namespace AtaLdap;
use Zend;
class AtaLdap
{
const ldapServer = *********;
const ldapPort = **********;
const ldapLogin = *********;
const ldapPass = *********;
const ldapBaseDn = ********;
/**
* Connect to LDAP via Zend LDAP module
*
* #return Zend\Ldap\Ldap
* #throws Zend\Ldap\Exception\LdapException
*/
public static function Zend()
{
$ldapOptions = [
'host' => self::ldapServer,
'port' => self::ldapPort,
'password' => self::ldapPass,
'bindRequiresDn' => TRUE,
'baseDn' => self::ldapBaseDn,
'username' => self::ldapLogin
];
$ldap = new Zend\Ldap\Ldap($ldapOptions);
$ldap->bind();
return $ldap->getResource();
}
public static function ZendRes()
{
return self::Zend()->getResource();
}
public static function deleteEntry($fromDN, $nameEntry, $contentEntry)
{
$res = self::Zend()->getResource();
$entryToDelete["$nameEntry"] = $contentEntry;
$deleteEntry = ldap_mod_del($res, $fromDN, $entryToDelete);
return $deleteEntry ? TRUE : FALSE;
}
Related
I want to execute ZF3 action with zf-console.
I can do this using zend-mvc-console module and it works fine.
For example.
Application/config/module.config.php:
'console' => [
'router' => [
'routes' => [
'cronroute' => [
'options' => [
'route' => 'sync',
'defaults' => [
'controller' => Controller\ConsoleController::class,
'action' => 'syncEvents'
]
]
]
]
]
],
Application/src/Controller/ConsoleController.php
class ConsoleController extends AbstractActionController
{
/**
* Entity manager.
* #var Doctrine\ORM\EntityManager
*/
private $entityManager;
/**
* User Manager
* #var Application\Service\UserManager
*/
private $userManager;
/**
* Constructor.
*/
public function __construct($entityManager, $userManager)
{
$this->entityManager = $entityManager;
$this->userManager = $userManager;
}
public function syncAction()
{
$response = $this->userManager->syncUserInfo();
return $response ? 'Sync Success' : 'Failed to sync';
}
}
But it says that it will be deprecated:
https://zendframework.github.io/zend-mvc-console/intro/#deprecated
It suggest to use zf-console from zfcampus:
https://github.com/zfcampus/zf-console
But I cannot find a way to execute Controller action or to use my build services (like UserManager).
There is example to build Zend Application and retrieve Service manager:
use Zend\Console\Console;
use Zend\Console\ColorInterface as Color;
use ZF\Console\Application;
use ZF\Console\Dispatcher;
chdir(dirname(__DIR__));
require __DIR__ . '/../vendor/autoload.php'; // Composer autoloader
$application = Zend\Mvc\Application::init(require 'config/application.config.php');
$services = $application->getServiceManager();
$buildModel = $services->get('My\BuildModel');
Is there a way to execute Controller action with it? Or Can I load my UserManager service?
I tried to get My UserManager:
$buildModel = $services->get('Application\Service\UserManager');
But receiving error:
PHP Fatal error: Uncaught exception 'Zend\ServiceManager\Exception\ServiceNotFoundException' with message 'Unable to resolve service "Application\Service\UserManager" to a factory; are you certain you provided it during configuration?' in /var/www/html/vendor/zendframework/zend-servicemanager/src/ServiceManager.php:687
The zend-mvc-console module does seem to be on the edge of deprecation. Just like you I was trying to implement zfcampus/zf-console. Since the mvc-console module seems to be (almost) deprecated, I suggest you use something different than (mvc) controllers for your console work. I used a class that can handle the call (in a way zf-console expects).
This is a dummy example I was working on for my project;
This is script that is called on the command line:
use Zend\Console\Console;
use Zend\ServiceManager\ServiceManager;
use Zend\Stdlib\ArrayUtils;
use Zend\Stdlib\Glob;
use ZF\Console\Application;
use ZF\Console\Dispatcher;
require_once __DIR__ . '/vendor/autoload.php'; // Composer autoloader
$configuration = [];
foreach (Glob::glob('config/{{*}}{{,*.local}}.php', Glob::GLOB_BRACE) as $file) {
$configuration = ArrayUtils::merge($configuration, include $file);
}
// Prepare the service manager
$smConfig = isset($config['service_manager']) ? $configuration['service_manager'] : [];
$smConfig = new \Zend\Mvc\Service\ServiceManagerConfig($smConfig);
$serviceManager = new ServiceManager();
$smConfig->configureServiceManager($serviceManager);
$serviceManager->setService('ApplicationConfig', $configuration);
// Load modules
$serviceManager->get('ModuleManager')->loadModules();
$routes = [
[
'name' => 'dumb',
'route' => '[--foo=]',
'description' => 'Some really cool feature',
'short_description' => 'Cool feature',
'options_descriptions' => [
'foo' => 'Lorem Ipsum',
],
'defaults' => [
'foo' => 'bar',
],
'handler' => function($route, $console) use ($serviceManager) {
$handler = new \Application\Command\DumbCommand();
return $handler($route, $console);
}
],
];
$config = $serviceManager->get('config');
$application = new Application(
$config['app'],
$config['version'],
$routes,
Console::getInstance(),
new Dispatcher()
);
$exit = $application->run();
exit($exit);
The handler function can use the service manager to inject any dependencies to the command handler:
'handler' => function($route, $console) use ($serviceManager) {
/** #var \Doctrine\ORM\EntityManager $entityManager */
$entityManager = $serviceManager->get(\Doctrine\ORM\EntityManager::class);
/** #var mixed $repository */
$contactRepository = $entityManager->getRepository(\Application\Entity\Contact::class);
$handler = new \Application\Command\DumbCommand($contactRepository);
return $handler($route, $console);
}
The command class is placed in a Command folder, it looks like:
<?php
namespace Application\Command;
use Application\Entity\Contact;
use Application\Repository\ContactRepository;
use Zend\Console\Adapter\AdapterInterface;
use ZF\Console\Route;
class DumbCommand
{
/** #var ContactRepository */
private $contactRepository;
public function __construct($contactRepository)
{
$this->contactRepository = $contactRepository;
}
/**
* #param Route $route
* #param AdapterInterface $console
* #throws \Doctrine\ORM\ORMException
*/
public function __invoke(Route $route, AdapterInterface $console)
{
$console->writeLine('Bob was here');
foreach ($this->contactRepository->findAll() as $item) {
/** #var Contact $item */
$console->writeLine($item->getFirstName() . ' was here');
}
}
}
(
This is my solution:
I addedd console command routes to my module.config.php files
'console' => array(
'commands' => array(
array(
'name' => 'sendemail',
'handler' => PostCommand::class,
),
array(
'name' => 'sendsms',
'handler' => SmsTransferCommand::class,
)
)
),
I created a console.php in /public (this will be run with arguments to start a CLI app)
use Zend\Console\Console;
use Zend\ServiceManager\ServiceManager;
use ZF\Console\Application;
use ZF\Console\Dispatcher;
chdir(dirname(__DIR__));
require_once 'vendor/autoload.php'; // Composer autoloader
// Prepare application and service manager
$appConfig = require 'config/application.config.php';
$application = Zend\Mvc\Application::init($appConfig);
$serviceManager = $application->getServiceManager();
// Load modules
$serviceManager->get('ModuleManager')->loadModules();
$config = $serviceManager->get('config');
$routes = $config['console']['commands']; // This depends on your structure, this is what I created (see. 1.)
$application = new Application(
$config['app'],
$config['version'],
$routes,
Console::getInstance(),
new Dispatcher($serviceManager) // Use service manager as a dependency injection container
);
$exit = $application->run();
exit($exit);
I separated my CLI command handlers into the src/Command folder. My CLI command handlers are services I have defined, created by factories. (This is why I use the service manager as the container - see. 2.)
[serviceEmail here is a local class variable, which is loaded by the factory of this command handler.]
/**
* #param Route $route
* #param AdapterInterface $console
*
* #return int
*/
public function __invoke(Route $route, AdapterInterface $console)
{
$mails = $this->serviceEmail->sendMailFromDb();
$console->writeLine('Sent mails: ' . \count($mails), ColorInterface::WHITE, ColorInterface::RED);
return 0;
}
We are using Doctrine 2 in our app, but due to our infrastructure, we do not have a static configuration for database connections. Instead, we have a collection of singletons in a service provider for each database we need to connect to, and we select a random database host for then when we connect.
Unfortunately, we are seeing some performance degradation in Doctrine's getRepository() function. I believe the issue is that Doctrine needs to generate its proxy classes at runtime (even in production) because we cannot figure out how to configure the CLI tools in order to create them at build time.
We are using the Laravel framework for the application.
Here's an example of our Laravel service provider which makes the repositories available for dependency injection.
<?php
use App\Database\Doctrine\Manager as DoctrineManager;
use Proprietary\ConnectionFactory;
use App\Database\Entities;
use App\Database\Repositories;
use App\Database\Constants\EntityConstants;
class DoctrineServiceProvider extends ServiceProvider
{
// Create a singleton for the Doctrine Manager. This class will handle entity manager generation.
$this->app->singleton(DoctrineManager::class, function ($app)
{
return new DoctrineManager(
$app->make(ConnectionFactory::class),
[
EntityConstants::ENTITY_CLASS_DATABASE1 => [app_path('Database/Entities/Database1')],
EntityConstants::ENTITY_CLASS_DATABASE2 => [app_path('Database/Entities/Database2')],
],
config('app.debug'),
$this->app->make(LoggerInterface::class)
);
});
// Register the first repository
$this->app->singleton(Repositories\Database1\RepositoryA1::class, function ($app)
{
return $app[DoctrineManager::class]
->getEntityManager(EntityConstants::ENTITY_CLASS_DATABASE1)
->getRepository(Entities\Database1\RepositoryA1::class);
});
// Register the second repository
$this->app->singleton(Repositories\Database1\RepositoryA2::class, function ($app)
{
return $app[DoctrineManager::class]
->getEntityManager(EntityConstants::ENTITY_CLASS_DATABASE1)
->getRepository(Entities\Database1\RepositoryA2::class);
});
// Register a repository for the second database
$this->app->singleton(Repositories\Database2\RepositoryB1::class, function ($app)
{
return $app[DoctrineManager::class]
->getEntityManager(EntityConstants::ENTITY_CLASS_DATABASE2)
->getRepository(Entities\Database2\RepositoryB1::class);
});
}
Here's the class that generates EntityManagers for Doctrine:
<?php
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Connections\MasterSlaveConnection;
use Proprietary\ConnectionFactory;
class Manager
{
private $c_factory;
private $paths;
private $connections = [];
private $entity_managers = [];
public function __construct(
ConnectionFactory $cf,
array $paths
)
{
$this->c_factory = $cf;
$this->paths = $paths;
}
public function getConnection($name, $partition = false, $region = false)
{
// Get a list of servers for this database and format them for use with Doctrine
$servers = self::formatServers($name, $this->c_factory->getServers($name, true, $partition, $region));
// Generate a connection for the entity manager using the servers we have.
$connection = DriverManager::getConnection(
array_merge([
'wrapperClass' => MasterSlaveConnection::class,
'driver' => 'pdo_mysql',
], $servers)
);
return $connection;
}
public function getEntityManager($name, $partition = false, $region = false)
{
// Should these things be cached somehow at build time?
$config = Setup::createAnnotationMetadataConfiguration($this->paths[$name], false);
$config->setAutoGenerateProxyClasses(true);
// Set up the connection
$connection = $this->getConnection($name, $partition, $region);
$entity_manager = EntityManager::create($connection, $config);
return $entity_manager;
}
// Converts servers from a format provided by our proprietary code to a format Doctrine can use.
private static function formatServers($db_name, array $servers)
{
$doctrine_servers = [
'slaves' => [],
];
foreach ($servers as $server)
{
// Format for Doctrine
$server = [
'user' => $server['username'],
'password' => $server['password'],
'host' => $server['hostname'],
'dbname' => $db_name,
'charset' => 'utf8',
];
// Masters can also be used as slaves.
$doctrine_servers['slaves'][] = $server;
// Servers are ordered by which is closest, and Doctrine only allows a
// single master, so if we already set one, don't overwrite it.
if ($server['is_master'] && !isset($doctrine_servers['master']))
{
$doctrine_servers['master'] = $server;
}
}
return $doctrine_servers;
}
}
Our service classes use dependency injection to get the repository singletons defined in the service provider. When we use the singletons for the first time, Doctrine will use the entity class defined in the service provider and get the connection associated with the repository.
Is there any way we can enable the CLI tools with this configuration? Are there any other ways that we can optimize this for use in production?
Thanks.
I was able to solve the problem thanks to a suggestion from the Doctrine IRC channel. Since the CLI tools can only handle a single database, I created a doctrine-cli directory containing a base-config.php file and a subdirectory for each of the databases we use.
Here's an example file structure:
doctrine-cli/
|- database1/
| |- cli-config.php
|- database2/
| |- cli-config.php
|- base-config.php
The base-config.php file looks like this:
<?php
use Symfony\Component\Console\Helper\HelperSet;
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
use App\Database\Doctrine\Manager as DoctrineManager;
use Proprietary\ConnectionFactory;
require __DIR__ . '/../bootstrap/autoload.php';
class DoctrineCLIBaseConfig
{
private $helper_set;
public function __construct($entity_constant, $entity_namespace)
{
$app = require_once __DIR__ . '/../bootstrap/app.php';
// Proprietary factory for getting our databse details
$connection_factory = new ConnectionFactory(...);
// Our class that parses the results from above and handles our Doctrine connection.
$manager = new DoctrineManager(
$connection_factory,
[$entity_constant => [app_path('Database/Entities/' . $entity_namespace)]],
false,
null,
null
);
$em = $manager->getEntityManager($entity_constant);
$this->helper_set = new HelperSet([
'db' => new ConnectionHelper($em->getConnection()),
'em' => new EntityManagerHelper($em),
]);
}
public function getHelperSet()
{
return $this->helper_set;
}
}
Here's an example cli-config.php from the database directory:
<?php
use App\Database\Constants\EntityConstants;
require __DIR__ . "/../base-config.php";
$config = new DoctrineCLIBaseConfig(
EntityConstants::ENTITY_CLASS_DATABASE1,
"database1"
);
return $config->getHelperSet();
Now, I'm able to cycle through each of the directories and run commands like so:
php ../../vendor/bin/doctrine orm:generate-proxies
For our build process, I wrote a simple shell script that cycles through the directories and runs the orm:generate-proxies command.
When I try to get the current directory with :
$this->container->getParameter('kernel.root_dir').'/../web/
I've got this error : Fatal error: Using $this when not in object context in C:\XXX on line 124
Code :
class AdminController {
/**
* Add event controller.
*
* #param Request $request Incoming request
* #param Application $app Silex application
*/
public function addEventAction(Request $request, Application $app) {
$event = new Event();
$types= $app['dao.type']->findAllSelectList();
$eventForm = $app['form.factory']->create(new EventType($types), $event);
$eventForm->handleRequest($request);
if ($eventForm->isSubmitted() && $eventForm->isValid()) {
var_dump($event->getCoverImageLink());
$file = $event->getCoverImageLink();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
var_dump($fileName);
//$path = $this->container->getParameter('kernel.root_dir').'/../web';//$this->get('kernel')->getRootDir() . '/../web';
var_dump($this);
$app['dao.event']->save($event);
$app['session']->getFlashBag()->add('success', 'The event was successfully created.');
}
return $app['twig']->render('event_form.html.twig', array(
'title' => 'New event',
'eventForm' => $eventForm->createView()));
}
How to fix this error please? What is the correct function to use?
It appears that you are using Silex, not Symfony 2. Being a very minimalistic framework, silex doesn't give you all the configuration and dependency injection goodies that Symfony does.
The easiest approach to be able to retrieve the application root, would be to define it yourself in bootstrap.php. Simply add something like this at the top:
define('APP_ROOT', __DIR__ . '/../');
Now you can just use the constant in your controller:
public function addEventAction(Request $request, Application $app) {
...
$path = APP_ROOT . '/../web';
...
}
I created a simple Phalcon project using Phalcon DevTools (1.2.3).
Now I want to use MongoDB for the database. How do I set this up correctly?
I came this far (see code below):
This is my config.php
<?php
return new \Phalcon\Config(array(
'database' => array(
'adapter' => 'Nosql', //Was 'Mysql', but Nosql is not supported?
'host' => 'localhost',
'username' => 'root',
'password' => '',
'dbname' => 'test',
),
'application' => array(
'controllersDir' => __DIR__ . '/../../app/controllers/',
'modelsDir' => __DIR__ . '/../../app/models/',
'viewsDir' => __DIR__ . '/../../app/views/',
'pluginsDir' => __DIR__ . '/../../app/plugins/',
'libraryDir' => __DIR__ . '/../../app/library/',
'cacheDir' => __DIR__ . '/../../app/cache/',
'baseUri' => 'localhost/',
)
));
This is my services.php
<?php
use Phalcon\DI\FactoryDefault,
Phalcon\Mvc\View,
Phalcon\Mvc\Url as UrlResolver,
//Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter, //Do I need this when I use Mongo?
Phalcon\Mvc\View\Engine\Volt as VoltEngine,
Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter,
Phalcon\Session\Adapter\Files as SessionAdapter;
/**
* The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
*/
$di = new FactoryDefault();
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->set('url', function() use ($config) {
$url = new UrlResolver();
$url->setBaseUri($config->application->baseUri);
return $url;
}, true);
/**
* Setting up the view component
*/
$di->set('view', function() use ($config) {
$view = new View();
$view->setViewsDir($config->application->viewsDir);
$view->registerEngines(array(
'.volt' => function($view, $di) use ($config) {
$volt = new VoltEngine($view, $di);
$volt->setOptions(array(
'compiledPath' => $config->application->cacheDir,
'compiledSeparator' => '_'
));
return $volt;
},
'.phtml' => 'Phalcon\Mvc\View\Engine\Php'
));
return $view;
}, true);
/**
* Database connection is created based in the parameters defined in the configuration file
*/
$di->set('mongo', function() use ($config) {
$mongo = new Mongo();
return $mongo->selectDb($config->database->dbname);
});
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set('modelsMetadata', function() {
return new MetaDataAdapter();
});
/**
* Start the session the first time some component request the session service
*/
$di->set('session', function() {
$session = new SessionAdapter();
$session->start();
return $session;
});
I altered the standard mysql db connection to be mongo, using the documentation.
But now I have to set up my database adapter in Config, but Nosql doesn't seem to work. DevTools throws this error in the terminal when trying to create a model:
Error: Adapter Nosql is not supported
When I do put in ' Mysql' for the adapter in the config and try to create a model, this is the error I get:
Error: SQLSTATE[HY000] [2002] No such file or directory
Does it need the Mysql adapter to be set in order to use Mongo/Nosql? Or should I put in something else for the adapter/config? Any ideas?
within service.php file where you have mongo service registered
$di->set('mongo', function() {
$mongo = new Mongo();
return $mongo->selectDb("DB_NAME");
}, true);
below that put following lines of code,
$di->set('collectionManager', function(){
return new Phalcon\Mvc\Collection\Manager();
}, true);
After the above is done you need to ensure that your model is extending from \Phalcon\Mvc\Collection
E.g. Customers.php
class Customers extends \Phalcon\Mvc\Collection
{
public $name;
public $email;
}
Once above is done, you can verify if everything is working fine as follows
$robot = new Customers();
$robot->email= "abc#test.com";
$robot->name = "XYZ";
if ($robot->save() == false)
{
echo "Could not be Saved!!";
}
else
{
echo "Data Saved!!";
}
You can put above code in any Controller-Action and try.
If everything goes well, you should be able to see one document created within Customer collection within your database of MongoDB.
Refer http://docs.phalconphp.com/en/latest/reference/odm.html for more..
$di->set('mongo', function() {
$user = 'blog';
$password = 'blog';
$host = 'localhost';
$port = '27017';
$db = 'blog';
$cn = sprintf('mongodb://%s:%d/%s',$host,$port,$db);
$con = new Mongo($cn,array('username'=>$user,'password'=>$password));
return $con->selectDB($db);
}, true);
As of the latest PhalconPHP, MongoDB seems to be a supported option for cache only, not for using as a replacement for the database.
It looks there is no MongoDB adapter for the Config component, only MySQL and couple of others (text based) in the incubator (https://github.com/phalcon/incubator).
You can still use MongoDB for the ACL and your Models though, see https://github.com/phalcon/incubator/tree/master/Library/Phalcon/Acl/Adapter and http://docs.phalconphp.com/en/latest/reference/odm.html#
I am fiddling with this issue and cannot resolve it - just wanted to check if anyone here can help with tips
I am loading the class and calling the constructor like this
include_once './Myaws.php';
$aws = new Myaws();
$aws->bucket = $images['config']['bucket'];
Myaws.php is as follows
class Myaws {
public $bucket;
function __construct() {
$this->aws = Aws::factory('./config/aws_config.php');
}
}
It works like a charm!
Now the issue
The './config/aws_config.php' is just an array that will change depending on the deployment stage - so I want to make it dynamic. Here is what I do and it doesnt work
include_once './Myaws.php';
$aws = new Myaws();
$aws->bucket = $images['config']['bucket'];
$aws->config = $images['config']['awsconfig'];
And in the Myaws.php, I change the following
class Myaws {
public $bucket;
public $config;
function __construct() {
$this->aws = Aws::factory($this->config);
}
}
It doesn't work :( and neither does the below one
include_once './Myaws.php';
$aws = new Myaws($images['config']['awsconfig']);
$aws->bucket = $images['config']['bucket'];
class Myaws {
public $bucket;
function __construct($config) {
$this->aws = Aws::factory($config);
}
}
This is pretty basic Oops and I don't seem to get it I think. Can anyone suggest me how can I make that variable $config dynamic?
I found the formatting on the included file vs in a passed array to be not 100% compatible. Also check the in the api docs how they use my_profile to pass those credentials.
here is a example of the current method I am using to generation the config
$aws = Aws::factory($this->getAwsConfig());
private function getAwsConfig()
{
return array(
// Bootstrap the configuration file with AWS specific features
'credentials' => array(
'key' => $this->awsKey,
'secret' => $this->awsSecret
),
'includes' => array('_aws'),
'services' => array(
// All AWS clients extend from 'default_settings'. Here we are
// overriding 'default_settings' with our default credentials and
// providing a default region setting.
'default_settings' => array(
'params' => array(
'region' => $this->awsRegion
)
)
)
);
}