{"id":18794562,"url":"https://github.com/effectra/db","last_synced_at":"2026-04-11T07:43:03.684Z","repository":{"id":182361770,"uuid":"655445440","full_name":"effectra/db","owner":"effectra","description":"Effectra\\Database is a PHP package that provides database connection and query execution functionality. It offers a convenient interface for interacting with different database drivers and executing common database operations.","archived":false,"fork":false,"pushed_at":"2023-12-12T18:51:56.000Z","size":105,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-05-21T16:13:10.587Z","etag":null,"topics":["connection","db","db-manager","mysql","oop","pdo","php","sqlite"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/effectra.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-06-18T22:58:53.000Z","updated_at":"2023-06-18T23:09:06.000Z","dependencies_parsed_at":"2023-07-19T19:31:40.324Z","dependency_job_id":"3bcd2148-4990-4722-9ec9-5f8bf0f379a0","html_url":"https://github.com/effectra/db","commit_stats":null,"previous_names":["effectra/db"],"tags_count":11,"template":false,"template_full_name":null,"purl":"pkg:github/effectra/db","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/effectra%2Fdb","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/effectra%2Fdb/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/effectra%2Fdb/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/effectra%2Fdb/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/effectra","download_url":"https://codeload.github.com/effectra/db/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/effectra%2Fdb/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31673067,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-10T17:19:37.612Z","status":"online","status_checked_at":"2026-04-11T02:00:05.776Z","response_time":54,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["connection","db","db-manager","mysql","oop","pdo","php","sqlite"],"created_at":"2024-11-07T21:29:47.666Z","updated_at":"2026-04-11T07:43:03.667Z","avatar_url":"https://github.com/effectra.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Effectra\\Database\n\nEffectra\\Database is a PHP package that provides database connection and query execution functionality. It offers a convenient interface for interacting with different database drivers and executing common database operations.\n\n## Installation\n\nYou can install the Effectra\\Database package via Composer. Simply run the following command:\n\n```bash\ncomposer require effectra/db\n```\n\n## Usage\n\n### Connection\n\nTo establish a database connection, you need to create an instance of the `Connection` class and call the `connect` method. The `connect` method retrieves the database configuration from the provided configuration file and returns a PDO object representing the database connection.\n\n```php\nuse Effectra\\Database\\Connection;\nuse Effectra\\Database\\Diver;\nuse Effectra\\Config\\ConfigDB;\n\n// Create a new instance of the Connection class\n\n$mysqlConfig = [\n    'driver' =\u003e 'mysql',\n    'host' =\u003e 'localhost',\n    'database' =\u003e 'your_database_name',\n    'username' =\u003e 'your_mysql_username',\n    'password' =\u003e 'your_mysql_password',\n    'charset' =\u003e 'utf8mb4',\n    'collation' =\u003e 'utf8mb4_unicode_ci',\n    // Add any additional options if needed\n];\n\n$connection = new Connection($mysqlConfig);\n```\n\nBy default, the `Connection` class supports MySQL and SQLite database drivers. You can easily add support for additional database drivers by implementing the `DriverInterface` and configuring the `Connection` class accordingly.\n\n### Query Execution\n\nOnce you have established a database connection, you can execute queries using the `DB` class. The `DB` class provides methods for executing common database operations such as `select`, `insert`, `update`, and `delete`.\n\n```php\nuse Effectra\\Database\\DB;\n\n// Establish the database connection\nDB::createConnection($con);\n// Establish the database event dispatcher\nDB::setEventDispatcher(new EventDispatcher());\n\n// Create a new instance of the DB class\n$db = new DB();\n\n// Execute a select query\n$data = $db-\u003ewithQuery('SELECT * FROM users')-\u003eget();\n\n// Execute an insert query\n$db-\u003etable('users')-\u003edata(['name' =\u003e 'Jane Doe','email'=\u003e 'janeDoe@mail.com'])-\u003einsert();\n\n// Execute an update query\n$db-\u003etable('users')-\u003edata(['name' =\u003e 'Jane Doe'])-\u003eupdate((new Condition())-\u003ewhere(['id' =\u003e 2]));\n\n```\n\nThe `DB` class provides a fluent interface for building and executing queries. You can chain methods to construct complex queries easily.\n\n\n### Error Handling\n\nIf an error occurs during query execution, the `DB` class will throw a `DatabaseException`. You can catch and handle this exception to gracefully handle database errors.\n\n```php\nuse Effectra\\Database\\Exception\\DatabaseException;\n\ntry {\n    $db-\u003etable('users')-\u003einsert( ['name' =\u003e 'John Doe']); // Missing 'email' field\n} catch (DatabaseException $e) {\n    // Handle the exception\n    echo \"Database Error: \" . $e-\u003egetMessage();\n}\n```\n\n# Model \n\n1. **Namespace:** The model is part of the `Effectra\\Database` namespace.\n\n2. **Traits:** The model uses the `ModelEventTrait` trait.\n\n3. **Properties:**\n   - `$connection`: An instance of the `DBInterface` representing the database connection.\n   - `$schema`: An array containing the schema of the model.\n   - `$entries`: An array containing the entries of the model.\n   - `$table`: The name of the table associated with the model.\n   - `$primaryKey`: The primary key for the model (default is 'id').\n   - `$keyType`: The data type of the primary key (default is 'int').\n   - `$incrementing`: Indicates if the model's ID is auto-incrementing (default is `true`).\n   - `const CREATED_AT` and `const UPDATED_AT`: Constants representing the names of \"created at\" and \"updated at\" columns.\n   - `$options`: Additional options for the model.\n   - `private static $query`: A static property to store the last executed database query.\n\n4. **Constructor:**\n   - The constructor sets the table name if not provided.\n\n5. **Methods:**\n   - `isEntriesCreated()`: Checks if entries have been created for the model.\n   - `createModelStructure()`: Creates the structure of the model, including schema and entries.\n   - `getDatabaseConnection()`: Gets a new database connection instance.\n   - `createSchema()`: Creates the schema for the model by fetching metadata from the database.\n   - `isSchemaCreated()`: Checks if the schema has been created for the model.\n   - `createEntriesFromSchema()`: Creates entries for the model based on the schema.\n   - Various methods for setting, getting, and manipulating options.\n   - `getSchema($property)`: Gets the schema entry for a specific property.\n   - `getEntries()`: Gets the entries for the model.\n   - `hasEntry($property)`: Checks if a specific entry exists in the model.\n   - `getEntry($property)`: Gets the value of a specific entry in the model.\n   - `setEntries($entries)`: Sets the entries for the model.\n   - `setEntry($property, $value)`: Sets a specific entry for the model.\n   - `removeEntry($property)`: Removes a specific entry from the model.\n   - Various magic methods (`__invoke`, `__set`, `__get`, `__toString`, `__isset`, `__unset`, `__callStatic`, `__call`) for dynamic property access and method calls.\n   - `toArray()`: Converts the model to an array representation.\n   - `toJson($flags = 0, $depth = 512)`: Converts the model to its JSON representation.\n   - `save()`: Saves the model to the database.\n   - `update()`: Updates the model in the database.\n   - `transaction($callback, ...$args)`: Performs a model operation in a transaction.\n   - `saveInTransaction($data = [])`: Saves the model in a transaction.\n   - `updateInTransaction()`: Updates the model in a transaction.\n   - Methods for retrieving models from the database (`get`, `all`, `limit`, `find`, `findBy`, `search`, `where`, `between`).\n   - Methods for deleting models from the database (`delete`, `deleteById`, `deleteByIds`, `deleteByIdsInTransaction`).\n   - `truncate()`: Truncates the model's table.\n   - `lastInsertId()`: Gets the last inserted ID for the model.\n   - `validateId($id)`: Validates a model ID.\n   - `setQuery($query)`: Sets the query instance for the model.\n   - `getQueryUsed()`: Gets the query instance used by the model.\n   - `getQueryUsedAsString()`: Gets the query instance used by the model as a string.\n   - `dd()`: Dumps the model class using Symfony's VarDumper.\n\nOverall, this model provides a flexible and extensible foundation for database interactions in a PHP application. It includes features for CRUD operations, query building, and transaction management. Additionally, it leverages traits for handling model events and uses Symfony's VarDumper for debugging purposes.\n\n\n## Basic Usage\n\n### create Model \n\n```php\nclass User extends Model {\n    \n}\n```\n\n### Retrieve a Record\n\n```php\n\n$user = User::find(1);\nprint_r($user);\n\necho $user-\u003eid;\n// or use method\necho $user-\u003egetId();\n\n```\n### Update a Record\n\n```php\n\n$user-\u003ename = 'Foo Bar';\n// or use method\n$user-\u003esetName('Foo Bar');\n\n$user-\u003eupdate();\n```\n### Save a Record\n\n```php\n$user = new User();\n\n$user-\u003ename = 'Foo Bar';\n$user-\u003eemail = 'FooBar@email.com';\n\n// or use method\n$user\n    -\u003esetName('Foo Bar');\n    -\u003esetEmail('FooBar@email.com');\n\n$user-\u003esave();\n```\n\n## Contributing\n\nContributions to the Effectra\\Database package are welcome. If you find any issues or have suggestions for improvement, please open an issue or submit a pull request on the GitHub repository.\n\n## License\n\nThe Effectra\\Database package is open-source software licensed under the [MIT license](https://opensource.org/licenses/MIT). See the `LICENSE` file for more information.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feffectra%2Fdb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Feffectra%2Fdb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Feffectra%2Fdb/lists"}