I want to have a simple form with PHP that takes YAML code as an input and stores it in to MongoDB when submitted. The update of records should also happen in the same way with editing yaml codes.
I am a beginner in programming and I don't want to use a framework or any complicated stuff just simple php form that takes yaml and converts to mongodb to be stored.
How should I do that?
Any recommendations or sample codes or if you know previous similar work?
Use the YAML Symfony component to load and parse the YAML file. The result of parsing the file will be a PHP array. This array can be easily saved into MongoDB:
1) Download Composer
curl -sS https://getcomposer.org/installer | php -- --install-dir=bin
2) Use composer to install the YAML Component. Create a composer.json file and add the following information:
{
"require": {
"symfony/yaml": "2.3.*#dev"
}
}
3) Install the component
$ php composer.phar install
4) Create a php file with the code to load from the YAML file and save the result to the db. Part of the following code was taken from the php.net mongodb tutorial :
<?php
// autoload.php will be installed by composer
require_once __DIR__.'/vendor/autoload.php';
use Symfony\Component\Yaml\Yaml;
// Parse YAML file
$yaml = Yaml::parse(__DIR__.'/path/to/file.yml');
// connect
$mongo = new \MongoClient();
// select a database
$db = $mongo->yaml;
// select a collection (analogous to a relational database's table)
$collection = $db->imports;
// add a record
$document = $yaml;
$collection->insert($document);
// find everything in the collection
$cursor = $collection->find();
echo "<pre>";
// iterate through the results
foreach ($cursor as $document) {
print_r($document);
}
echo "</pre>";
Check out the data in MongoDB :
> show dbs;
yaml 0.203125GB
> use yaml;
switched to db yaml
> show collections;
imports
system.indexes
> db.imports.find();
Related
I'm using following:
PHP 7.2
MongoDB 3.4
Pecl 1.5.2
I'm working on a Laravel project. It uses MongoDB as database. I have few collections on which I have to create Mongo Views using Laravel migration. I was wondering whether its possible to create Mongodb Views using PHP. Currently I have a work around. I have created a JavaScript file which has MongoDB db.createView() query in it. It also takes view name and collection name as parameters. Following is my work around. $db has database name, $view has view name, $collection has collection name and $script has the path to the JavaScript file. This code I'm writing in migration class's up() method.
$cmd = "mongo $db --eval \"var view='$view', collection='$collection'\" $script";
exec($cmd);
In my Javascript file, I have code something like following
db.createView(view, collection, <aggregate query>);
So as everyone can see, I'm running terminal command from PHP to make views. So is there any PHP function in mongo library to make mongo views?
If you're using mongo with Laravel, I'm going to assume you're using jenssegers/mongodb to use it with Eloquent.
So, let's assume you have your mongo database set up as your 'mongodb' database connection. You need the MongoDB\Database for your database. You can get this with:
$mongo = app('db')->connection('mongodb')->getMongoDB();
Of course, if you're not using jenssegers/mongodb, you can still do the same thing with mongodb/mongodb as well.
$mongo = (new MongoDB\Client)->selectDatabase($db);
This has a method called command (see https://docs.mongodb.com/php-library/current/reference/method/MongoDBDatabase-command/), which corresponds to the db.runCommand method from the mongo cli. db.createView calls that method (see https://docs.mongodb.com/manual/reference/method/db.createView/#db.createView)
So, you can use $mongo->command to create the view like this:
$mongo->command([
'create' => $view,
'viewOn' => $collection,
'pipeline' => $aggregateQuery,
'collation' => ['locale' => 'en'],
]);
You can use this library mongoPhpLibrary
This will make your work easy
I'm trying to get the PHP_CodeCoverage library working for the simplest possible case to create an HTML code coverage report, and failing. I have PHP and Xdebug installed. I would rather not specify the versions of those that I am using because I'm hoping there is something simple I am overlooking, but I will provide those details upon request. For now, suffice to say, I am using very new versions of them.
To make this as simple as possible, I distilled it down to 2 files and I still can't get it to do what I want. The 2 files are the automatically generated vendor/autoload.php created by composer when installing the coverage library, and the file that is using the library. This file is at project-root/src/CoverageTest.php. The autoload file is at project-root/vendor/autoload.php.
When I run php src/CoverageTest.php from the terminal, it does generate an HTML report. When I view the report, inside the Code Coverage table, there is only a single row with everything set to "n/a" or "0/0". It does not report any coverage as existing or missing. It doesn't say anything about specific files, classes, functions, or lines. To a large extent the code you see in this test file is the same as what appears on their README page. Here is the code:
<?php
require __DIR__.'/../vendor/autoload.php';
$coverage = new \SebastianBergmann\CodeCoverage\CodeCoverage;
$coverage->start('<name of test>');
class MathGenius
{
public function add($first, $second)
{
return $first + $second;
}
}
$guru = new MathGenius();
$sum = $guru->add(1, 1);
$coverage->stop();
$writer = new \SebastianBergmann\CodeCoverage\Report\Html\Facade;
$writer->process($coverage, __DIR__.'/../code-coverage-report');
It only reports on whitelisted files and directories. This is how I got the example I posted to work. Before creating the coverage object, I created a filter object, like so:
$filter = new \SebastianBergmann\CodeCoverage\Filter();
Since that example was only attempting to cover itself, I whitelisted that file with the filter like this:
$filter->addFileToWhitelist(__FILE__);
Then when creating the coverage object, you pass in the filter like so:
$coverage = new \SebastianBergmann\CodeCoverage\CodeCoverage(null, $filter);
Here is the full code for the fixed version of the code from the question:
<?php
require __DIR__.'/../vendor/autoload.php';
$filter = new \SebastianBergmann\CodeCoverage\Filter();
$filter->addFileToWhitelist(__FILE__);
$coverage = new \SebastianBergmann\CodeCoverage\CodeCoverage(null, $filter);
$coverage->start('<name of test>');
class MathGenius
{
public function add($first, $second)
{
return $first + $second;
}
}
$guru = new MathGenius();
$sum = $guru->add(1, 1);
$coverage->stop();
$writer = new \SebastianBergmann\CodeCoverage\Report\Html\Facade;
$writer->process($coverage, __DIR__.'/../code-coverage-report');
I'm trying to build a project with Propel these days. I did the basic 'bookstore' tutorial on propelorm.org/documentation/02-buildtime.html, but when I'm trying to finally insert the generated sql code via propel, to fill the database, the following error is thrown:
[Exception] Unable to parse contents of "/sqldb.map".
Unfortunately I've got no idea what went wrong; I followed the tutorial as precisely as possible.
Information about my installation and what I've done so far:
1) Localhost installation (Mac OS 10.8.5) with PHP 5.4.27 (DOM Module, PDO and SPL enabled) and MySQL 5.6.19.
2) successfully parsed Composer.json with:
{
"require": {
"propel/propel": "~2.0#dev"
},
"autoload": {
"classmap": ["bookstoreDb/generated-classes/"]
}
}
3) created a schema.xml with foreign keys, exactly like in the tutorial (propelorm.org/documentation/02-buildtime.html).
4) created a config file, propel.yaml, in subfolder 'conf', again like in the tutorial.
5) used the propel scripts to generate the necessary sql (propel sql:build), model (propel model:build) and configuration files (propel config:convert). The result of these commands are as indicated as in the tutorial.
6) created the database 'bookstore' successfully via terminal.
7) trying to insert the sql code via propel sql:insert. Now the error as described above is thrown:
[Exception] Unable to parse contents of "/sqldb.map".
Here is the index.php of the project:
// setup the autoloading
require_once 'vendor/autoload.php';
// setup Propel
require_once 'bookstoreDb/generated-conf/config.php';
// Here I get the parse error: parse error in ../bookstore/bookstoreDb/generated-classes/Base/Author.php on line 138
$author = new Author();
$author->setFirstName('Jane');
$author->setLastName('Austen');
$author->save();
And here the config.php:
$serviceContainer = \Propel\Runtime\Propel::getServiceContainer();
$serviceContainer->checkVersion('2.0.0-dev');
$serviceContainer->setAdapterClass('bookstore', 'mysql');
$manager = new \Propel\Runtime\Connection\ConnectionManagerSingle();
$manager->setConfiguration(array (
'classname' => 'Propel\\Runtime\\Connection\\ConnectionWrapper',
'dsn' => 'mysql:host=localhost;dbname=bookstore',
'user' => 'root',
'password' => 'password',
'attributes' =>
array (
'ATTR_EMULATE_PREPARES' => false,
),
));
$manager->setName('bookstore');
$serviceContainer->setConnectionManager('bookstore', $manager);
$serviceContainer->setDefaultDatasource('bookstore');
Where may be the problem? And is there some other way to setup a basic project? I'd appreciate every help! Thanks!
I submitted an issue for this: https://github.com/propelorm/Propel2/issues/694
SqlBuildCommand uses configured sql-dir
$manager->setWorkingDirectory($generatorConfig->getSection('paths')['sqlDir'])
SqlInsertCommand only uses the command line option
$manager->setWorkingDirectory($input->getOption('sql-dir'));
adding --sql-dir option with correct sql dir to propel sql:insert does work
fix is submitted https://github.com/propelorm/Propel2/pull/695 but not merged yet
I have defined some fixtures in doctrine.
When i try to run using this
php app/console doctrine:fixtures:load then it asks me to purge the database.
is it possible to load it without purging database.
I remeber Django has fixtures which can be loaded in separate tables without purging existing database
Use the --append option
php app/console help doctrine:fixtures:load
Usage:
doctrine:fixtures:load [--fixtures[="..."]] [--append] [--em="..."] [--purge-with-truncate]
Options:
--fixtures The directory or file to load data fixtures from. (multiple values allowed)
--append Append the data fixtures instead of deleting all data from the database first.
--em The entity manager to use for this command.
--purge-with-truncate Purge data by using a database-level TRUNCATE statement
DoctrineFixtures are nice for the first init of an empty database or in development - but not in production.
Take a look at DoctrineMigrations and symfonys DcotrineMigrationsBundle, this is a good and safe way to migrate your database in production.
It is possible to update previously added data to DB (which was loaded by running app/console doctrine:fixtures:load). I used EntityManager->createQuery for that.
But I still wonder if there is or ever will be an opportunity to do it by simply running an app/console command. Something like app/console doctrine:schema:update --force, but applied to the data itself.
For now I had to write a ton of code to get my data updated and appended properly. For example to make --append work I had to write the following:
class LoadCategoryData implements FixtureInterface
{
/**
* {#inheritDoc}
*/
public function load(ObjectManager $em)
{
//a category has name and shortcut name (st)
$categories = array (
[0]=> array('name' => 'foo', 'st' = 'bar'),
...
);
foreach ($categories as $cat) {
$query = $em->createQuery(
"SELECT c
FROM MyBundle:Category c
WHERE c.st = ?1"
)->setParameter(1, $cat['st'])->getResult();
if (count($query) == 0) {
$c = new Category();
$c->setName($cat['name']);
$c->setSt($cat['st']);
$em->persist($c);
}
$em->flush();
}
}
}
I'm trying to import a mailing list from CSV to my DATABASE. I have two models in my Laravel which is responsible for doing this: Target and Mailing (one Target has many Mailings)
I'm using Queue system with Beanstalkd. I'm using:
Queue::push('ImportCSV', array(
'file' => $file->getClientOriginalName(),
'target' => $name
));
To push my jobs and then I have the ImportCSV job class:
class ImportCSV
{
public function fire($job, $data)
{
Log::info("Starting to add {$data['target']} to database");
$target = new Target();
$target->name = $data['target'];
$target->save();
$reader = new \EasyCSV\Reader($data['file']);
// There must be a Email field in CSV file
/*if(!in_array('Email', $reader->getHeaders() ))
throw new Exception("Email field not found", 1);*/
while ($row = $reader->getRow())
{
$mailing = new Mailing();
$mailing->target()->associate($target);
$mailing->email = $row['Email'];
$mailing->save();
}
Log::info("Mailing list {$target->name} added to database");
$job->delete();
}
}
All the code seems to be working since I get these messages in my Log file
[2013-09-10 21:03:25] log.INFO: Starting to add TEst to database [] []
[2013-09-10 21:03:25] log.INFO: Mailing list TEst added to database [] []
But no records are added to my database. How should I use models inside a job? I already tested it in a Controller for example and everything works fine
Since you don't see other errors, I'm thinking this is an environment issue.
First - environments
Make sure your call to php artisan queue:listen (or queue:work, if applicable) is using the correct environment so the correct database is getting used:
$ php artisan queue:listen --env=YOUR_ENV
Here's a post on setting up queues in Laravel 4 which might be helpful for more information.
Second - namespaces
As you (apparently?) aren't seeing any PHP errors, this is less likely, but another idea:
If your class is namespaced, you may need to use the \ character to get your models, which are in the global namespace.
// From:
$mailing = new Mailing();
// To:
$mailing = new \Mailing();