MongoDB PHP library how to create database - php

I use MongoDB PHP library in the client object I can see the method for drop a database, how can I create a new database?

You probably have problems with the naming.
In mongodb a DB is called an Index and a tabe called a Collection.
You will find createIndex in the docs:
http://mongodb.github.io/mongo-php-library/api/namespace-MongoDB.Operation.html
https://docs.mongodb.org/v3.0/reference/method/db.collection.createIndex/

the namespace database is automatically create if it does not exist when we create collection
use MongoDB\Driver\Manager;
use MongoDB\Database;
$manager = new Manager("mongodb://localhost:27017");
$database = new Database($manager, 'newDataBase');
var_dump($database->createCollection('CollectionName'));
sorry i keep learning

Related

Programmatically load Entity in symfony

I am trying to load in Entity classes and use within a loop in order to load content in dynamically from files into relating tables.
Is there any way i can load in all Entity files from the following
use AppBundle\Entity\aaPostcode;
use AppBundle\Entity\abPostcode;
use AppBundle\Entity\acPostcode;
use AppBundle\Entity\adPostcode;
in such a way like this?
use AppBundle\Entity\*
Not sure if this is possible in Symfony.
My next issue is using the the prefixedEntity within a loop like so -
new $entityPrefix
When i am setting $entityPrefix to the following format
$entityPrefix = str_replace([".csv"], "", $entityFilename) . "Postcode" . '()';
which returns the string of
"abPostcode()"
can anyone advise as to why calling
new $entityPrefix;
is not working
Thanks in advance for any help!
trying to call
new $entityPrefix();
returns
[Symfony\Component\Debug\Exception\ClassNotFoundException]
Attempted to load class "abPostcode" from the global namespace.
Did you forget a "use" statement for "AppBundle\Entity\abPostcode"?
even when i current am hrd coding the use stament to call
use AppBundle\Entity\abPostcode;
You can't instanciate dynamically your class without ginving the full namespace. Try that :
$namespace = "AppBundle\Entity\\";
$entityName = "YourEntity";
$namespace .= $entityName;
$class = new $namespace();
This is working for me...
I solved this by pulling out the functionality into a helper and running a switch statement based on the input - in this case a {prefix}
I kinda ran into this issue migrating data from one database type to another. IE: Oracle to MySQL. With hundreds of tables the use section would get big.
This is on Symfony 5.2.x BTW.
When I run a query using a standard repository or a repository linked to the table I can call the entity with its full namespace.
$oracle = $em2->getRepository(\App\Entity\Oracle\Appoints::class)->Appoints();
So I did not have to load "use App\Entity\Oracle\Appoints
Then I can create a new object in the same way:
$mysqlObject = new \App\Entity\OracleAppPoints();

Delete document in ElasticSearch using Elastica library

I have Elastica library and implemented ElasticSearch in my project.
I want to delete document from index.
How to delete documents by ids in elasticsearch using elastica ?
I have tried multiple solution but it still not working!
TIA
For deleting documents by ids you can use deleteByQuery() function which is a function for index in elastica, so you can use it like this:
$matchPhraseQuery = new MatchPhrase("_id", /*id of document you want to delete*/);
$client = new Client(/*your client config*/);
$index = $client->getIndex("/*Your index name*/");
$index->deleteByQuery($matchPhraseQuery);

Laravel - override connection but model still returns data from previous connection

So this is my process. I run a command and it creates a new connection. It then sets that connection as default. THIS works perfectly.
It also overrides another connection. However, since we can only have one default instead of creating a new connection and setting it to default it simply copies the old connection / replaces the database info and then overrides that connection.
I then immediately create a model that uses this connection. I even go into it and dump out $this->getConnection() and see that its pulled in my new settings and configs. My issue is that when I do a ->all() I am getting info from the PREVIOUS overridden connection. I have no clue why.
Here is a sample of my code:
public function handle()
{
if (!is_null($this->env = $this->option('env'))) {
(new Dotenv(base_path(), ".env.{$this->env}"))->overload();
}
$this->setClientConnection();
dd(\Override::getModel('User')->changeConnection('webApp')->get()->pluck('login_name', 'users_id'));
}
/**
* Create the database and a temporary connection
*
* #return null
*/
protected function setClientConnection()
{
$clientDb = env('DB_DATABASE');
$userDb = env('DB_APP_DATABASE');
// Create temporary connection
$newConnection = config('database.connections.data');
$newConnection['database'] = $clientDb;
config(['database.connections.' . $clientDb => $newConnection]);
// Set new connection as default
config(['database.default' => $clientDb]);
// Override Webapp database
$newUserConnection = config('database.connections.webApp');
$newUserConnection['database'] = $userDb;
config(['database.connections.webApp' => $newUserConnection]);
}
Just to reiterate, creating a new connection and setting it to default works perfectly. Creating a new connection and using it to override an existing connection SEEMS to work. config('database.connections.webApp') gives the new connection info. (new App\User)->getConnection() returns the proper config and database is set to the new database. looking at the model object, all appears right. Then I go to make a ->all() call and it pulls in the overridden connection and pulls from the old database.
P.S. the changeConnection method i added to test out some things and to look at different protected attributes. Most of my dumping i did from there and it LOOKS like it should be using the new connection...till it actually makes the call...then no go.
When you run get() on an Eloquent Model it runs the query on the Illuminate\Query\Builder object (after going through the Illuminate\Eloquent\Query\Builder wrapper function).
TheIlluminate\Query\Builder object stores a reference of the connection object used for the query.
Since your model is created first and then the connection is changed, the Query Builder object still uses the old connection
To solve this issue you need to create a fresh instance of the model query builder with the new connection
There are multiple ways to do this:
Use the static function on like so: User::on('connection_name')->find($userId)
Use the newFromBuilder method like so: $model->newFromBuilder($model->getAttributes, 'connection_name')
Use the newQuery method to get a fresh Eloquent builder like so: $model->setConnection('connection_name')->newQuery()->find($userId)
Use the fresh method like so: $model->setConnection('connection_name')->fresh().
Do note however that the fresh method fires a new query whereas the other options set the connection without firing a new query.
Your choice of function would be based on
Whether you already have a model instance or whether you want to use static methods and
Whether you only need the builder object (like #3) or you actually need the model instance

how to use bindFunc method in redbeanphp?

i am working on a project that need to work with spatial object in mysql and i choose redbeanphp as ORM system in this project. i found redbeanphp so terrific and awesome.
i search in google and found this link that say bindFunc method can help me in working with spatial object but i cannot find any example for using this method.
how this method work and how can i use this method?
According to the database part of that website you linked:
As of RedBeanPHP 4.1 you can bind an SQL function to a column. This is
useful for wrapping values when reading from / writing to the
database. For instance, to use MySQL spatial data types you need to
prepare the columns like this:
R::bindFunc( 'read', 'location.point', 'asText' );
R::bindFunc( 'write', 'location.point', 'GeomFromText' );
$location = R::dispense( 'location' );
$location->point = 'POINT(14 6)';
//inserts using GeomFromText() function
R::store( $location );
//to unbind a function, pass NULL:
R::bindFunc( 'read', 'location.point', NULL );
This function was added to support spatial datatypes in MySQL as shown above. The documentation isn't amazing, so I recommend looking at the source code on Github if you want to dig in deeper.

Use nested transformers in Laravel 5

In my Laravel 5 app, I'm implementing Transformers and Fractal.
I've got in my example two different models: User and UserLogin. Every User can have multiple UserLogins (I've already added a one-to-many relationship between them). Now I want to "clean" my response, which returns an User with his UserLogins. So I've created two transformers, and I thought that I should call a transformer inside the other one inside his return, like here:
"UserLogins"=> Fractal::collection($user->userLogins, new UserLoginTransformer).......
Unfortunately it doesn't work and the error is that it doesn't find fractal library (which is correctly imported).
What could be the problem?
Finally found the solution.
Fractal class does not exists, I cannot make simplier than that.
And you weren't correctly using the library.
So, the solution :
use \League\Fractal\Manager;
use \League\Fractal\Resource\Collection as FractalCollection;
$fractal = new Manager();
$resource = new FractalCollection($user->userLogins, new UserLoginTransformer);
return $fractal->createData($resource)->toArray();

Categories