ORM layer that creates models, config and database on the fly

Related tags

Database redbean
Overview

RedBeanPHP 5

Build Status

RedBeanPHP is an easy to use ORM tool for PHP.

  • Automatically creates tables and columns as you go
  • No configuration, just fire and forget
  • No complicated package tools, no autoloaders, just ONE file

Installation (recommended)

Download RedBeanPHP from the website:

https://redbeanphp.com/download

Extract the archive and put it in your PHP project, voila!

Optional: sha256sum and check signature.

Installation via Composer (not recommended)

Just open your composer.json file and add the package name (e.g. "gabordemooij/redbean": "dev-master") in your require list.

{
    "require": {
        "gabordemooij/redbean": "dev-master"
    }
}

NOTE: You will find many examples on the RedBean website make use of RedBean's R class. Because of namespaced autoloading in Composer, this class will be available as \RedbeanPHP\R instead of R. If you desire to use the much shorter R alias, you can add a use statement at the beginning of your code:

use \RedBeanPHP\R as R;

NOTE: It is important to note that when using RedBeanPHP with Composer, there are some extra precautions needed when working with Models. Due to the namespace requirements of Composer, when creating Models we need to use the SimpleModel to extend, not RedBean_SimpleModel. Furthermore, we need to specify the namespace of the SimpleModel, so a full example of using a Model with RedBean with Composer is as follows:

use \RedBeanPHP\R;

class Model_User extends \RedBeanPHP\SimpleModel
{
    ...
}

Notice that we also need to add the use \RedBeanPHP\R statement so that we can use the R:: shortcut within the Model.

Quick Example

How we store a book object with RedBeanPHP:

$book = R::dispense("book");
$book->author = "Santa Claus";
$book->title = "Secrets of Christmas";
$id = R::store( $book );

Yep, it's that simple.

More information

For more information about RedBeanPHP please consult the RedBeanPHP website:

https://www.redbeanphp.com/

Comments
  • Is it possible to escape a colon in a bound parameters, to prevent it from being treated as a bound parameter?

    Is it possible to escape a colon in a bound parameters, to prevent it from being treated as a bound parameter?

    In the screenshot, i'm using Regular expression to search in a table that contains some json. problem is, when adding a bound parameter to the query, it treats the json seperator : as the start of a new named parameter. is there a work around for this?

    Fig1: Query is valid img Fig2: Redbean seems to be treating the colon in the REGEXP as a bound parameter img2

    opened by r3wt 39
  • Proposition for a new SQLHelper

    Proposition for a new SQLHelper

    Intent

    This issue intends to discuss a PROPOSITION to add a new SQLHelper to redbean: I was looking at this post on redbean forum and noticed a promising idea from @daviddeutsch called Rx:

    R::$x->project->name('project x')->code(200)->find();
    

    Usage

    Using SQL operators (=, >, <, <>, LIKE, BETWEEN, IN, etc):

    $R::
        $x->project
            ->name('like', '%project x')
            ->priority('>', 5)
            ->created_at('between', [$time1, $time2])
            ->find();
    

    And possibility to group SQL conditions:

    R::$x->project
        ->name('like', '%secret%')->AND->priority('>', 9)
        ->OR
        ->OPEN
            ->code('in', [007, 51])->AND->created_at('between', [$time1, $time2])
        ->CLOSE
        ->find()
    

    Sane defaults:

    Default SQL operator is = and default SQL construct between conditions is AND, so Rx original syntax would still be allowed :)

    R::$x->project->name('project x')->code(200)->find();
    

    I know redbean philosophy about query writers, but this does not looks like over engineering IMMO and would be a great addition. Maybe I could implement this feature, but need some feedback to improve the idea.

    @gabordemooij What do you think?

    cheers!

    opened by marcioAlmada 33
  • Let's talk about Instantiation

    Let's talk about Instantiation

    Limitations of the monolithic Facade

    Sorry if this is a broad topic, but during my current downtime to develop some stuff, I ran into serious restrictions with RedBean, came to a number of conclusions and would love to discuss them with other users.

    I have two major use cases right now:

    Deploying RedBean across domains

    The Problem

    The monolithic Facade works well if you're developing a monolithic app. Meaning: a single database in a single domain (speaking in DDD terms). What I ran into was that I have multiple interdependent and interacting domains.

    I have one app - hotbox (a package creator similar to the packaging part composer) - that creates a main database for cross-project information and a further database for each project, all of which have their own logging and so forth. Then I use hotbox in a client-facing server app, mangrove-server which also has its own tables, including logging and so forth.

    I do not want to have both apps speak to the same database because that would mean that I have to either use prefixes or implement tons of namespacing within my tables. Also - when I kill a project in hotbox, I can get rid of the database instead of expensive sorting-out operations.

    First, cumbersome solution

    What I did initially was to use a single instance of RedBean and implement a database switcher. That only gets you so far, though, because you end up switching databases a lot. The bandaid that I used was that the only way that applications talk to eachother was through an API facade with static methods like so:

    
    public static function registerPackage( $package, $branch )
    {
        $current_db = R::$currentDB;
    
        R::selectDatabase(self::$config->database->name);
    
        // Business Logic goes here
    
        R::selectDatabase($current_db);
    
        return true;
    }
    
    

    But this only solves matters across applications (and it's highly debatable how elegant the solution is), not within an application.

    Current Solution

    What I needed here was instances, plain and simple. So I'm currently writing daviddeutsch/redbean-instance to make that happen. Right now, it's a facade wrapper that registers a facade as an instance and implement a __call() function that relays method calls to static method calls (more below under 'downsides').

    Also note that I wrote further rb plugins and in those plugins, I had to inject a facade parameter to the plugin static method, like so:

    public static function prefix( $prefix, $facade=null )
    {
        if ( is_null($facade) ) {
            $class = get_class(R::$writer);
        } else {
            $class = get_class($facade::$writer);
        }
    

    That's the only way I can ensure that I end up modifying the correct facade - again a restriction of a monolithic facade to begin with.

    Downsides of the current approach

    I had to write a translation function from static to regular method calls since:

    $r2db2 = R::instance();
    
    // Works
    $project = $r2db2::dispense('project');
    
    // --- MyApp.php ---
    
    MyApp::deploy();
    
    class MyApp
    {
        public static $db;
    
        public static function deploy()
        {
            self::$db = R::instance();
        }
    }
    
    // --- MyProject.php ---
    class MyProject
    {
        public function stuff()
        {
            // Nope.
            $user = MyApp::$db::dispense('user');
    
            // Yup, but: eww.
            $user = MyApp::$db->dispense('user');
    
            // Also completely breaks Rx:
            $user = MyApp::$db::_('user'); // Nope again
    
            // I can make _() work, but again, eww:
            $user = MyApp::$db->_('user');
    
            // FindHelper is broken though, with no recovery:
            $user = MyApp::$db::$r->user->one()->find(); // *shudders
        }
    
    }
    

    So, the bottom line is: This makes Facade calls mad uglies.

    Of course, I can (and probably will have to) convert the $x static in Rx to a property, but I'm jumping through hoop after hoop. Will have to rethink the Rx design.

    Likely new approach

    It appears, though, that I will have to copy most of the facade into a new class that emulates most of the behavior of the Facade (see below for further discussions on the concept of the facade).

    This also solves the other problem I currently have deploying RedBean with clients is that I'm still running into some with PHP 5.2. So for them, __callStatic() isn't an option anyhow, killing plugins.

    Deploying RedBean in a CMS context

    The Problem

    Usually, a CMS context means a single database, so that's all fine and dandy. But you also have lots of prefixes - one for the cms itself and one for the component that you're working on.

    Current Solution

    Right now, I have written to get around this with the daviddeutsch/redbean-prefix plugin

    Downsides

    Prefixes obviously have lots of downsides, but that's the nature of the beast and it's not in my powers to change that.

    Broader ruminations on the viability of the Facade

    To be quite honest, using Redbean "in the wild" (meaning: painful, but unfortunately non-negotiable situations) shows the weak points of a Facade approach pretty quickly. I still like the Facade a lot for quick and dirty work, but the more I think about it, conceptually, the more I see the Facade as a specialized version of an Instance.

    My current conclusion is: Maybe a RedBeanPHP\Instance should be part of Redbean, with RedBeanPHP\Facade being a wrapper for that.

    The biggest problem, of course, is that the syntax between static and instance calls are different, '->' instead of '::'. That means your code becomes less portable across implementations.

    Furthermore: design of plugins

    I've looked at a couple other plugins during my development and mostly what I see is that people write a R::ext() call straight into the class file. That's not really instance safe. Might not matter that much if you always want to have all your extensions, but can be problematic (let alone wasteful) as soon as you're in a CMS context where apps are talking to eachother, each with their own extensions.

    In my opinion, a plugin should only supply the class, not inject itself into the Facade automatically.

    opened by daviddeutsch 29
  • Replace RedUNIT

    Replace RedUNIT

    • Use PHPUnit instead of RedUNIT
    • Replace Spike PHP Coverage with some other tool (ideas?)
    • Learn-by-test (http://derickbailey.github.io/backbone.marionette/docs/backbone.marionette.html)
    opened by gabordemooij 26
  • Get instance of database connection

    Get instance of database connection

    At Multiple database here https://redbeanphp.com/index.php?p=/database

    static calls are used to switch databases. Could it be made possible to get an object instance representing the database connection?

    contribution 
    opened by flip111 23
  • PHP Fatal error:  Class 'RedBean_QueryWriter_Cubrid' not found

    PHP Fatal error: Class 'RedBean_QueryWriter_Cubrid' not found

    I suppose you've forgotten to include CUBRID RedBean driver, haven't you? Or should I download the DB plug-in and require_once in the code manually?

    Here is the error I receive when I try to connect to a CUBRID database.

    PHP Fatal error:  Class 'RedBean_QueryWriter_Cubrid' not found in /home/user/localhost/rb.php on line 5565
    

    Right now I am writing a small PHP app which uses RedBeanPHP to store data into a CUBRID database.

    opened by CUBRID 23
  • Website has some issues on mobile

    Website has some issues on mobile

    When visiting the website on a mobile device (specifically iPhone 13 Pro Max using Chrome), there seems to be an issue with the menu overlay.

    The overlay seems to be shown by default, and attempts to dismiss it (i.e. tapping in the overlay) just reveal the menu. Screenshots as follows:

    image

    image

    bug report (confirmed) resolved 
    opened by benmajor 22
  • Website does not work

    Website does not work

    Hi,

    I have been trying to gain access to the website (https://www.redbeanphp.com/) for several days and always get the following error ERR_CONNECTION_RESET. Is there any other place I can dowload the documentation?

    Thanks,

    Jerome

    resolved researching intake 
    opened by martinjeromelouis 22
  • Checking for active transaction

    Checking for active transaction

    Right now, we have rollback, commit and begin methods. There should be also a method that allows us to check if there is any active transaction. This is especially useful for databases that don't support nested transactions (SQLite). PDO already has it: http://www.php.net/manual/pl/pdo.intransaction.php

    opened by rr- 22
  • RedBean extras, community participation/plugins

    RedBean extras, community participation/plugins

    So, I think it makes sense to make this into a ticket. On the mailing list, we already talked a little about this. To recap:

    • While we are building RB4, a lot of the new and fancy stuff should and will happen in plugins - this keeps the core clean and concise
    • Ideally, each plugin should be maintained mostly by one member of the community who takes responsibility for it
    • It is also the responsibility of the maintainer to keep up the same level of testability and "documentation by test" noted in #308
    • Having a separate repository is probably the way to go. What about redbean-extras? Although I would prefer redbean-sugar, but I might be pushing it with the coated beans idea
    • One of the goals is that with redbean-sugar, we create a source for building a custom RB distribution
    opened by daviddeutsch 21
  • Feature: allow for duplicate key inserts?

    Feature: allow for duplicate key inserts?

    Currently, RB requires to my understanding high overhead or manual SQL for performing "upserts" against tables with duplicate keys. I'd appreciate a solution that is able to use "REPLACE INTO" or "INSERT IGNORE" or similar mechanisms.

    opened by andig 20
Releases(v5.7.3)
  • v5.7.3(Oct 8, 2022)

  • v5.7.2(Apr 2, 2022)

  • v5.7.1(Oct 31, 2021)

    • Added compatibility with PHP 8.1 (thanks Ipsod)
    • Fixed a minor bug in setPDO() that failed to set isConnected flag (thanks DengWang)
    • Added 4th parameter to BeanCollection to pass a meta mask (thanks MangoMarcus)
    • Added initial support for PHPStan/Psalm-annotations (thanks Craig Francis)
    Source code(tar.gz)
    Source code(zip)
  • v5.7(Apr 3, 2021)

    • Added pstr($x) function to easily generate [$x, PDO::PARAM_STR] for you
    • Added pint($x) function to easily generate [$x, PDO::PARAM_INT] for you
    • Added R::camelfy() convience function
    • Added R::uncamelfy() convience function
    • Improved PHP-8 compatibility
    • OODBBean::equals now accepts NULL and simply returns FALSE
    • Improved some source comments
    Source code(tar.gz)
    Source code(zip)
  • v5.6.2(Nov 28, 2020)

    • Fixes a minor syntax compatibility issue in PHP8
    • Fixed issue with R::bindFunc and shared lists in some cases
    • Added PHP8 to Travis-CI test matrix (does not work yet)
    Source code(tar.gz)
    Source code(zip)
  • v5.6(Oct 3, 2020)

    • Added DDL-templates (Gabor)
    • Added bean->info() and R::findFromSQL() (Gabor)
    • Added getDatabaseServerVersion() (Gabor)
    • Fix unnecessary widening when storing 1 in a MySQL TINYINT(1) column #839. (Gabor, thanks davidsickmiller)
    • Preventing RedBean from trying to call protected or private methods (Lynesth)
    • Allowing the use of __call in the model (Lynesth)
    • Allow overriding stringifyFetch with setPDO (Gabor)
    • Adjust setPDO in RPDO to avoid having pdo instance replaced (Gabor)
    • Added support for SQL Select Snippets in CTE-Queries (Gabor)
    • Added support for MySQL8 (Gabor)
    Source code(tar.gz)
    Source code(zip)
  • v5.5(Apr 30, 2020)

    • SQL-Extensions @joined/@own/@shared** (Lynesth)
    • R::countChildren()/R::countParents() (Gabor)
    • Finder::onmap()/R::loadJoined() (Gabor)
    • Execution bit removed from PHP files (Travispaul)
    • Plug-ins may now also contain underscores (Lynesth)
    • Arrays are now allowed as meta mask (Lynesth)
    • Minor performance improvement in convertToBeans (Lynesth)
    • Improved checking in LIMIT-1 glue (Lynesth)
    • Fix issues in Hybrid mode (Gabor/MadTeddy)
    • Make convertToBean compatible with getRow (Gabor/Flip111)
    • Fix in OODBBean changelist (AlexanderYIXIAO)
    • Fix in testPartialBeansAtSetup (AlexanderYIXIAO)
    • Removal of AutoResolve (Gabor/Lynesth/Rayraz)*
    Source code(tar.gz)
    Source code(zip)
  • v5.4.2(Dec 26, 2019)

  • v5.4.1(Dec 7, 2019)

    • Fix issue with default values in combination with Partial Beans mode
    • Fix minor issue in Unit Test system
    • Update test file for PHP 7.4 compatibility
    Source code(tar.gz)
    Source code(zip)
  • v5.4(Sep 28, 2019)

    Debug Logger now correctly handles typed bindings (author AbygailG)
    R::store( $beans, $unfreezeIfNecessary); (author Gabor, inspiration from PR David Sickmiller)
    R::storeAll( $beans, $unfreezeIfNecessary);
    R::findForUpdate() (author Gabor)
    R::traverse(...,function( ,$depth){}) passes depth level (author Lynesth)
    Allow findLike (and the likes) to use "IS NULL" conditions (author Lynesth)
    Have trash/trashAll return number of deleted beans (author Lynesth)
    Fixed Facade::removeToolBoxByKey removing the toolbox (thanks Dmelo)
    R::getRow() now adheres to return type array (author Nucc1)
    R::setAllowFluidTransactions() (thanks Lynesth and Marios88)
    Peformance improvement of R::diff() (author Lynesth)
    Fix Cache prevent a second FOR-UPDATE SQL query (author Gabor)
    Additional unit tests
    Improvement source code documentation
    
    Source code(tar.gz)
    Source code(zip)
  • v5.3.1(May 28, 2019)

  • v5.3(Apr 6, 2019)

    Explicit parameter type binding (thanks Lynesth)
    Added countTaggedAll() and countTagged()
    Added R::useFeatureSet()
    Added nmMap() for complex FindMulti mappings
    Released independent SQN library for quick SQL notation in PHP
    Added R::noNuke()
    Support for MySQL SSL: useMysqlSSL( $key, $cert, $ca, $id )
    Support for PHP 7.3
    
    Source code(tar.gz)
    Source code(zip)
  • v5.1(Apr 3, 2018)

    Changes in version 5.1 (2 April 2018, Easter Edition)

    Added R::trashBatch($type, $ids) to trash a batch of beans in one statement
    Added R::hunt( $type, $query, $params ) to find and trash beans in one statement
    Added Debugger::setOverrideCLIOutput() to override PHP_SAPI in Debugger
    Improved API documentation box()/unbox()
    Improved API documentation matchUp
    Make QuickExport compatible with PHP versions 5.4 and below
    Add warning in API documentation regarding use of findLast()
    Mark R::findLast() as deprecated
    Fixed compatibility issue with PHP 7.2 (thanks Lynesth)
    Increases execution speed if no conditions are set (thanks Lynesth)
    Added DispenseHelper::setEnforceNamingPolicy() to disable naming policy
    Faster return from __call() if no model (thanks Lynesth)
    Updated README and Composer JSON (thanks Rotzbua)
    Added Composer Model documentation (thanks Ben Major)
    Fix Facade::convertToBean documentation (thanks Diogo Oliveira de Melo)
    Reached 100% test coverage
    Code clean-ups
    Improved other documentation
    Tiny Query Builder now available as plugin for your convenience
    Improved performance of modifySchema() (thanks davidsickmiller)
    Fixed a compatibility issue with ProxySQL in connection mechanism
    

    See https://redbeanphp.com/index.php?p=/changelog

    Source code(tar.gz)
    Source code(zip)
  • v5.0(Oct 27, 2017)

    Simplified Exceptions for load() functions
    By default R::load() and R::loadForUpdate() will now throw exceptions if a bean cannot be loaded due to a lock timeout
    Support for JSON columns has been extended.
    Update .gitignore (thanks jreklund)
    Update Composer aliasing in readme (thanks benmajor)
    Make filter function in look() optional
    Added R::loadForUpdate() to load and lock a bean
    Separate versions for MySQL, Postgres and SQLite as well as combined
    Storage of partial beans
    R::look(...) perform query and put result in template
    R::matchUp(...) match-and-update in one go (easy to create login functionality)
    R::csv(...) create a CSV file from a query
    R::diff(...) returns a diff between a pair of beans
    Added setEnforceUTF8Encoding to fix issue with stringifying binary data
    Added exists() to bean to check for relation
    Fixed notice in Facade inproper use of reset()
    Added missing validations for findOrDispense and findOneOrDispense
    Support for utf8mb4_unicode_520_ci (thanks Johan)
    
    Source code(tar.gz)
    Source code(zip)
  • v4.3.4(Apr 9, 2017)

Owner
Gabor de Mooij
Creator of the Citrine Programming Language http://citrine-lang.org
Gabor de Mooij
Orm is a simple database abstraction layer that supports postgresql.

Orm What is it Orm is a simple database abstraction layer that supports postgresql. Welcome to join us or star us for encouragement. Requires php 8.1

null 2 Sep 28, 2022
Analogue ORM : Data Mapper ORM for Laravel/PHP

(this project is looking for a new maintainer) Analogue ORM Analogue is a flexible, easy-to-use ORM for PHP. It is a transposition of the Eloquent ORM

Analogue ORM 632 Dec 13, 2022
The Enobrev\ORM library is a small framework of classes meant to be used for simply mapping a mysql database to PHP classes, and for creating simply SQL statements using those classes.

The Enobrev\ORM library is a small framework of classes meant to be used for simply mapping a mysql database to PHP classes, and for creating simply SQL statements using those classes.

Mark Armendariz 0 Jan 7, 2022
A Redis based, fully automated and scalable database cache layer for Laravel

Lada Cache A Redis based, fully automated and scalable database cache layer for Laravel Contributors wanted! Have a look at the open issues and send m

Matt 501 Dec 30, 2022
Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer

Spot DataMapper ORM v2.0 Spot v2.x is built on the Doctrine DBAL, and targets PHP 5.4+. The aim of Spot is to be a lightweight DataMapper alternative

Spot ORM 602 Dec 27, 2022
Doctrine Database Abstraction Layer

Doctrine DBAL 4.0-dev 3.0 2.13 N/A N/A Powerful database abstraction layer with many features for database schema introspection, schema management and

Doctrine 8.9k Dec 28, 2022
Laravel 5 - Repositories to abstract the database layer

Laravel 5 Repositories Laravel 5 Repositories is used to abstract the data layer, making our application more flexible to maintain. See versions: 1.0.

Anderson Andrade 4k Jan 6, 2023
Database Abstraction Layer, Schema Introspection, Schema Generation, Query Builders

Cycle DBAL Secure, multiple SQL dialects (MySQL, PostgreSQL, SQLite, SQLServer), schema introspection, schema declaration, smart identifier wrappers,

Cycle ORM 30 Oct 18, 2022
A drop-in Doctrine ORM 2 implementation for Laravel 5+ and Lumen

Laravel Doctrine ORM A drop-in Doctrine ORM 2 implementation for Laravel 5+ $scientist = new Scientist( 'Albert', 'Einstein' ); $scientist->a

Laravel Doctrine 777 Dec 17, 2022
MongoDB ORM that includes support for references,embed and multilevel inheritance.

Introduction Features Requirements Installation Setup Database Basic Usage - CRUD Relationship - Reference Relationship - Embed Collection Inheritance

Michael Gan 202 Nov 17, 2022
Doctrine Object Relational Mapper (ORM)

3.0.x 2.9.x 2.8.x Doctrine 2 is an object-relational mapper (ORM) for PHP 7.1+ that provides transparent persistence for PHP objects. It sits on top o

Doctrine 9.5k Jan 2, 2023
Baum is an implementation of the Nested Set pattern for Laravel's Eloquent ORM.

Baum Baum is an implementation of the Nested Set pattern for Laravel 5's Eloquent ORM. For Laravel 4.2.x compatibility, check the 1.0.x branch branch

Estanislau Trepat 2.2k Jan 3, 2023
Propel2 is an open-source high-performance Object-Relational Mapping (ORM) for modern PHP

Propel2 Propel2 is an open-source Object-Relational Mapping (ORM) for PHP. Requirements Propel uses the following Symfony Components: Config Console F

Propel 1.2k Dec 27, 2022
PHP DataMapper, ORM

Cycle ORM Cycle is PHP DataMapper, ORM and Data Modelling engine designed to safely work in classic and daemonized PHP applications (like RoadRunner).

Cycle ORM 1.1k Jan 8, 2023
Extensions for the Eloquent ORM

Sofa/Eloquence Easy and flexible extensions for the Eloquent ORM. Currently available extensions: Searchable query - crazy-simple fulltext search thro

Jarek Tkaczyk 1.1k Dec 20, 2022
Ouzo Framework - PHP MVC ORM

Ouzo is a PHP MVC framework with built-in ORM and util libraries. PHP 8.0 or later is required. We believe in clean code and simplicity. We value unit

Ouzo 69 Dec 27, 2022
Builds Cycle ORM schemas from OpenAPI 3 component schemas

Phanua OpenAPI 3 + Jane + Cycle ORM = ?? Phanua builds Cycle ORM schemas from OpenAPI 3 component schemas. Released under the MIT License. WARNING: Th

Matthew Turland 5 Dec 26, 2022
Simple Enum cast for Eloquent ORM using myclabs/php-enum.

Enum cast for Eloquent Simple Enum cast for Eloquent ORM using myclabs/php-enum. Requirements PHP 7.3 or higher Laravel 8.0 or higher Installation You

Orkhan Ahmadov 5 Apr 21, 2022
Extra RedBean ORM

RedBeanPHP 5 RedBeanPHP is an easy to use ORM tool for PHP. Automatically creates tables and columns as you go No configuration, just fire and forget

GingTeam Development 5 Nov 23, 2022