Latest / CyberSecurity Summary / Persistence in PHP with the Doctrine ORM
Transcript
- 0:00Speaker 1: Okay, let's unpack this. Imagine writing like ten thousand lines
- 0:04Speaker 1: of pristine, beautifully architected, object oriented PHP code.
- 0:09Speaker 2: Oh that's the dream, right right.
- 0:11Speaker 1: You have your classes, your properties, your inheritance trees, all
- 0:14Speaker 1: your objects are just neatly interacting with one another.
- 0:16Speaker 2: Yeah, a perfect domain model exactly.
- 0:19Speaker 1: And then after all that elegant design, you have to just,
- 0:22Speaker 1: you know, smash that entire architecture into a flat, rigid,
- 0:26Speaker 1: two dimensional grid of database tables.
- 0:29Speaker 2: It really is the ultimate architectural heartbreak. I mean it's
- 0:32Speaker 2: a huge problem.
- 0:33Speaker 1: It totally is because your PHP application it speaks this
- 0:36Speaker 1: rich language of objects, but your database it only understands tables, columns, rows,
- 0:42Speaker 1: and foreign keys.
- 0:44Speaker 2: Right. They are two completely different paradigms, and.
- 0:47Speaker 1: Bridging that gap manually usually means writing just endless, repetitive
- 0:50Speaker 1: seqle queries just to save affect your data. It completely
- 0:54Speaker 1: bogs down your whole workflow, it does.
- 0:56Speaker 2: I mean, that fundamental disconnect is honestly one of the
- 0:58Speaker 2: biggest hurdles in opp location development. Oh. Absolutely, You spend
- 1:02Speaker 2: all this energy building a domain model that represents your
- 1:05Speaker 2: business logic, only to have to write dozens of mapping.
- 1:08Speaker 1: Functions have to tear those objects.
- 1:10Speaker 2: Apart, exactly, you tear them apart just to fit them
- 1:12Speaker 2: into a relational database structure. It completely disrupts your focus.
- 1:17Speaker 1: You stop thinking about how your app should behave and
- 1:19Speaker 1: you start agonizing over like how to keep your memory
- 1:23Speaker 1: state synchronized with a hard drive.
- 1:25Speaker 2: Which is exactly what we want to avoid.
- 1:27Speaker 1: So for today's deep dive, we're looking at the solution
- 1:30Speaker 1: to that disconnect. We are talking about the doctrine ORM
- 1:34Speaker 1: or object relational mapper, a.
- 1:36Speaker 2: Life saver for PHP developers, truly.
- 1:40Speaker 1: We're going to decode how doctrine acts as the ultimate
- 1:43Speaker 1: highly skilled UN translator, working flawlessly between those two entirely
- 1:48Speaker 1: different languages.
- 1:49Speaker 2: Like that analogy a UN translator, right, And we'll.
- 1:52Speaker 1: Use a standard blog engine as our guiding example today
- 1:55Speaker 1: to see how it takes all that heavy lifting off
- 1:57Speaker 1: your plate.
- 1:57Speaker 2: Sounds perfect.
- 1:58Speaker 1: So to understand how doc doctrine pulls this off, we
- 2:01Speaker 1: have to start with the brain of the operation, which
- 2:03Speaker 1: is the entity manager.
- 2:04Speaker 2: Yeah, the core of doctrine.
- 2:06Speaker 1: Now, in doctrine, the actual data objects like your blog
- 2:11Speaker 1: posts or user profiles. Those are called entities. But these entities,
- 2:15Speaker 1: they're just plain old PHP objects.
- 2:18Speaker 2: Right, They don't extend some massive database library or anything.
- 2:21Speaker 1: No, they have absolutely no idea that a database even exists.
- 2:25Speaker 2: And you know that is very much by design. It
- 2:28Speaker 2: relies on a specific architectural pattern called the data mapper.
- 2:31Speaker 1: Okay, data mapper, How is that different from what other
- 2:34Speaker 1: frameworks do?
- 2:35Speaker 2: Well? In some other frameworks, you might see the active.
- 2:37Speaker 1: Record pattern, oh right, where the object itself has a save.
- 2:41Speaker 2: Mefit exactly, it talks directly to the database, but doctrine
- 2:44Speaker 2: deliberately separates those concerns.
- 2:46Speaker 1: So the entity's only job is to just hold your data.
- 2:48Speaker 2: Yes, and the entity manager is a completely separate service
- 2:52Speaker 2: that handles the really complex job of mapping that data
- 2:55Speaker 2: and saving it.
- 2:56Speaker 1: Using something called the unit of work.
- 2:57Speaker 2: Right, Yes, the unit of work. It's a crucial concept here.
- 2:59Speaker 1: The unit of work concept is honestly brilliant. I like
- 3:03Speaker 1: to think of the entity manager as a highly experienced
- 3:06Speaker 1: waiter taking your order at a really busy restaurant.
- 3:08Speaker 2: Okay, walk me through that.
- 3:10Speaker 1: Well, the application you're making changes. You tell the waiter
- 3:13Speaker 1: you want a steak, then you change your mind to chicken.
- 3:17Speaker 1: Then you add a side of fries that maybe cancel
- 3:20Speaker 1: a drink order. That waiter doesn't sprint back to the kitchen,
- 3:24Speaker 1: which is our database in this case, every single time
- 3:27Speaker 1: you open your mouth.
- 3:28Speaker 2: Now, if the waiter did that, the kitchen would be
- 3:29Speaker 2: completely overwhelmed exactly, which is exactly what happens when an
- 3:33Speaker 2: application fires off a new sequel query for every single
- 3:38Speaker 2: tiny variable chain.
- 3:39Speaker 1: It's chaos. So instead, the waiter stays at your table
- 3:43Speaker 1: writing everything down on their night pad.
- 3:45Speaker 2: And that notepad is the unit of work spot on.
- 3:47Speaker 1: It tracks all the modifications, the new additions, the items
- 3:50Speaker 1: you want removed. And it is only when you are
- 3:53Speaker 1: completely finished and the waiter walks over to the kitchen
- 3:56Speaker 1: enhance in that final consolidated ticket that the database actually
- 4:00Speaker 1: gets to work.
- 4:01Speaker 2: And in doctrine, handing in that ticket is done by
- 4:04Speaker 2: calling a specific method called flush flush. And what's fascinating
- 4:08Speaker 2: here is the optimization that happens when you call that
- 4:11Speaker 2: flush method. It's really the core power of doctrine.
- 4:14Speaker 1: You mean an example of that optimization.
- 4:15Speaker 2: Well, let's say you retrieve a blog post entity from
- 4:19Speaker 2: the database. In your code, you execute a change like
- 4:22Speaker 2: you set my entity name to my name. Then maybe
- 4:25Speaker 2: immediately after a different function changes that name again to
- 4:29Speaker 2: let's say.
- 4:30Speaker 1: Kevin, so change twice in memory.
- 4:32Speaker 2: Right, Doctrine's unit of work is tracking both of those
- 4:35Speaker 2: changes on its notepad. But when you finally call flush,
- 4:39Speaker 2: Doctrine doesn't waste time running two separate update queries.
- 4:42Speaker 1: Wait, really, it just skips the first one exactly.
- 4:45Speaker 2: It compares the original state of the object to its
- 4:47Speaker 2: final state, realizes only the final name matters, and issues
- 4:51Speaker 2: a single sequel query. Oh wow, yeah, just one update
- 4:55Speaker 2: my entity set name equals kevin where it equals thirteen
- 4:58Speaker 2: to twelve using prepared statements.
- 5:00Speaker 1: That is incredibly efficient.
- 5:02Speaker 2: It is, and it handles the other entity manager states
- 5:05Speaker 2: just as seamlessly, like find to retrieve an object, or
- 5:09Speaker 2: if you create a brand new entity, you use persist.
- 5:12Speaker 1: Which basically introduces it to the entity manager. Right tilling
- 5:15Speaker 1: Doctrine like, hey, watch this new.
- 5:16Speaker 2: Object exactly, and if you want to delete something, you
- 5:18Speaker 2: call removed.
- 5:19Speaker 1: So you just schedule it for deletion. Doctrine notes it
- 5:22Speaker 1: on the notepad and waits for the flesh.
- 5:24Speaker 2: Yes, and by sinking everything in one massive batch during
- 5:29Speaker 2: that flesh call, Doctrine can wrap all those changes in
- 5:32Speaker 2: a single database transaction.
- 5:34Speaker 1: Okay, why is that transaction part so important?
- 5:36Speaker 2: Because if anything goes wrong during the flesh, say you're
- 5:40Speaker 2: saving a new user, generating their profile, and creating a
- 5:43Speaker 2: welcome post, all at once, a lot of inserts, right,
- 5:46Speaker 2: and if the very last insertion fails because of a
- 5:49Speaker 2: network kickup, the database automatically rolls back to its exact
- 5:53Speaker 2: previous state.
- 5:54Speaker 1: Oh that's huge.
- 5:55Speaker 2: Yeah, keeping data perfectly consistent, you are completely protected from
- 5:59Speaker 2: ending up with half saved.
- 6:00Speaker 1: Data, which could corrupt your entire system. Okay, so the
- 6:04Speaker 1: entity manager is our waiter, perfectly batching our changes. But
- 6:08Speaker 1: it can only do that if it has a map.
- 6:10Speaker 1: It has to know that the title property in our
- 6:14Speaker 1: PHP object corresponds to a specific text column in our
- 6:18Speaker 1: SQL database. Naturally, but we just established that our entities
- 6:22Speaker 1: are plain PHP objects with no database logic. So where
- 6:27Speaker 1: does this map actually live?
- 6:29Speaker 2: So doctrine uses doc block annotations to build this map
- 6:33Speaker 2: annotations right, These are specially formatted comments placed directly inside
- 6:38Speaker 2: your PHP code, right above your classes and properties.
- 6:41Speaker 1: Wait, like literally in the code comments exactly.
- 6:44Speaker 2: You use specific tags like at entity or at table
- 6:48Speaker 2: above your class to declare it as a database table,
- 6:51Speaker 2: and tags like at column at id or at generated
- 6:55Speaker 2: value above your properties to define exactly how they map
- 6:58Speaker 2: to the columns.
- 6:58Speaker 1: Here's where it gets really interesting, though, because putting database
- 7:02Speaker 1: configurations right inside PHP comments doesn't that clutter up the code?
- 7:07Speaker 1: I mean, because my entity is suddenly deeply aware of
- 7:10Speaker 1: my database schema. We're usually taught to keep those things
- 7:13Speaker 1: strictly separated, right.
- 7:14Speaker 2: Yeah, I mean that's a very common point of friction
- 7:16Speaker 2: for developers transitioning to doctrine. I can imagine the purest
- 7:20Speaker 2: view is that your domain objects should be completely oblivious
- 7:23Speaker 2: to how they're stored, maybe using separate XML or Yammel
- 7:27Speaker 2: configuration files right. But practically speaking, keeping the mapping information
- 7:32Speaker 2: right next to the code vastly improves readability and maintenance.
- 7:36Speaker 1: Because it's right there in front of you.
- 7:37Speaker 2: Exactly when you look at a property, you instantly know
- 7:41Speaker 2: how it behaves in the database. You don't have to
- 7:43Speaker 2: hunt through massive external files to see if a string
- 7:46Speaker 2: can be null.
- 7:47Speaker 1: I guess I could see the practical trade off there,
- 7:49Speaker 1: And the way doctrine handles mapping types is pretty cool too. Oh.
- 7:52Speaker 2: The type casting is a massive timesaver.
- 7:55Speaker 1: Because doctrine types aren't purely PHP, and they are purely SQL.
- 8:00Speaker 2: Right right. They act as a transparent bridge. For instance,
- 8:03Speaker 2: Doctrine's text type becomes a standard string in your PHP.
- 8:06Speaker 1: App, but in the SQL database.
- 8:09Speaker 2: It's automatically stored as a c lobrie, a character large
- 8:12Speaker 2: object suitable for massive blocks of texts.
- 8:15Speaker 1: That's so seamless it is.
- 8:18Speaker 2: But we do need to point out a really critical
- 8:20Speaker 2: limitation here. While Doctrine handles the mapping, it does not
- 8:23Speaker 2: do data validation. If your annotation says a column has
- 8:27Speaker 2: a max length of fifty characters, Doctrine builds the database
- 8:31Speaker 2: column to that exact spec. But if a user submits
- 8:34Speaker 2: one hundred characters, Doctrine won't stop them. It won't stop them,
- 8:38Speaker 2: it will try to save it, and the database will
- 8:39Speaker 2: throw a fatal error. You still have to validate user
- 8:42Speaker 2: inputs separately, So it's.
- 8:44Speaker 1: A mapp or not a bouncer. Yeah, good to know.
- 8:47Speaker 1: But honestly, the absolute best part of defining all those
- 8:50Speaker 1: annotations is the command line magic.
- 8:53Speaker 2: Oh, the schema tool.
- 8:54Speaker 1: Yeah, by running I think it's a an orm colon
- 8:58Speaker 1: schema tool Colon create, that's the one. Doctrine reads all
- 9:01Speaker 1: those annotations and automatically generates the entire underlying database schema.
- 9:06Speaker 2: Cables, columns, primary.
- 9:07Speaker 1: Keys, without the developer writing a single line of sequel.
- 9:11Speaker 1: It completely removes the busy work.
- 9:13Speaker 2: It's incredible for bootstrapping a new project.
- 9:15Speaker 1: Okay, so mapping a single blog post is straightforward, but
- 9:18Speaker 1: things get complicated fast when we add comments and tags right.
- 9:21Speaker 2: Enterprise apps aren't just isolated tables exactly.
- 9:24Speaker 1: Relational databases use foreign keys and joining tables for this.
- 9:28Speaker 1: How does doctrine handle these complex webs well.
- 9:31Speaker 2: It manages them through association types, also defined using annotations
- 9:37Speaker 2: like at onetominy for a post to comments relationship.
- 9:40Speaker 1: Or at minutomany for posts to tags exactly.
- 9:43Speaker 2: But to make these relationships work, you have to understand
- 9:46Speaker 2: a concept that trips up almost everyone.
- 9:49Speaker 1: At first, let me guess the owning side versus the
- 9:52Speaker 1: inverse side.
- 9:53Speaker 2: Yes, using the inverse buy and mapped by attributes, it
- 9:56Speaker 2: is a notorious stumbling block.
- 9:58Speaker 1: It totally is. I like to use a dog leash
- 10:00Speaker 1: analogy for this one.
- 10:01Speaker 2: Okay, let's hear it.
- 10:02Speaker 1: So the owning side is like holding the leash of
- 10:04Speaker 1: a dog. The dog, which is the inverse side, might
- 10:07Speaker 1: know it belongs to you. But if you don't actually
- 10:10Speaker 1: grab the leash, meaning setting the owning side and the
- 10:13Speaker 1: codoctrine won't save the connection.
- 10:16Speaker 2: That's a great way to put it because the crucial
- 10:18Speaker 2: rule is that doctrine only manages the owning side of
- 10:20Speaker 2: an association. So if you have a method like ad
- 10:23Speaker 2: comment on your post entity, you can't just push the
- 10:26Speaker 2: comment into an array. That method must include a line
- 10:30Speaker 2: like comment arrow set post.
- 10:32Speaker 1: You have to explicitly grab the leash exactly.
- 10:36Speaker 2: If you don't, the relationship evaporates when you flush.
- 10:39Speaker 1: And speaking of arrays, doctrine doesn't actually use standard PHP
- 10:42Speaker 1: arrays for these relationships right now.
- 10:45Speaker 2: It uses a special class called array collection.
- 10:48Speaker 1: Why is that If it's just a list of comments,
- 10:50Speaker 1: why not just use a normal array?
- 10:52Speaker 2: Because a normal array is completely passive. Doctrine needs to
- 10:57Speaker 2: track the internal state of that collection.
- 10:59Speaker 1: Oh, to know what to sync with the database.
- 11:02Speaker 2: Right it acts like a standard PHP array, but provides
- 11:05Speaker 2: the hidden hooks. Doctrine needs to figure out what to
- 11:08Speaker 2: update or delete.
- 11:09Speaker 1: And that enables some really cool features like orphan removal equals.
- 11:12Speaker 2: True yes, automatically deleting tags that are no longer linked
- 11:16Speaker 2: to any post.
- 11:17Speaker 1: Or cascade equals persist.
- 11:18Speaker 2: Or saving a post automatically saves all the brand new
- 11:21Speaker 2: comments attached to it.
- 11:22Speaker 1: But if we connect this to the bigger picture, all
- 11:25Speaker 1: these webs of objects must impact performance.
- 11:28Speaker 2: Right massively, especially regarding how the data is loaded. By default,
- 11:32Speaker 2: Doctrine uses lazy loading, meaning.
- 11:35Speaker 1: It only fetches the relations when you explicitly ask for them.
- 11:38Speaker 2: Right, If you ask for a post, it leaves the
- 11:41Speaker 2: comments behind. If your code asks for them later, it
- 11:44Speaker 2: quietly fires off a second query to fetch them, which.
- 11:47Speaker 1: Saves memory initially. But what if I know I need
- 11:50Speaker 1: all the comments? Isn't that second query wasteful?
- 11:52Speaker 2: It is? That's the classic N plus one query problem.
- 11:55Speaker 2: To fix it, you switch to eager loading using fetch
- 11:58Speaker 2: equals eager in your annotations, so.
- 12:00Speaker 1: It fishes them immediately in one big joint exactly. Okay,
- 12:03Speaker 1: so we successfully save these interconnected webs of objects, but
- 12:07Speaker 1: how do we get them back out efficiently without resorting
- 12:10Speaker 1: to raw SQL.
- 12:11Speaker 2: We need a new way to ask for our data,
- 12:13Speaker 2: and that is Doctrine query language or BIKIL. Yes, and
- 12:17Speaker 2: the massive paradigm shift here is that DQL queries the
- 12:20Speaker 2: object models entities, not the database tables.
- 12:23Speaker 1: Right, So you're not writing select star from posts left
- 12:27Speaker 1: joint comments on.
- 12:28Speaker 2: Now you write something like select pc from blog slash
- 12:32Speaker 2: entity slash post p lft joinp dot comments c.
- 12:36Speaker 1: That is wild. You just use the properties.
- 12:39Speaker 2: It's extremely powerful. And to keep these organized, Doctrine uses
- 12:42Speaker 2: entity repositories, which.
- 12:44Speaker 1: Is the table data gateway pattern exactly.
- 12:47Speaker 2: The base repositories give you magic methods like fine by
- 12:50Speaker 2: title where you don't even write query logic.
- 12:52Speaker 1: But for complex stuff we use custom repositories and the
- 12:55Speaker 1: career builder.
- 12:55Speaker 2: Right. Yes, you build a query by calling methods like create,
- 12:59Speaker 2: query builder left, join ad select. It translates seamlessly into SQL.
- 13:04Speaker 1: So what does this all mean for security? Because I'm
- 13:07Speaker 1: thinking about SQL injection? Like if someone types quote r
- 13:10Speaker 1: quote a quote equals quote.
- 13:12Speaker 2: A ah, the classic exploit.
- 13:14Speaker 1: Right, does the query builders stop that?
- 13:16Speaker 2: Absolutely? The query builders set parameter method acts as a
- 13:20Speaker 2: built in security guard. It automatically escapes inputs some malicious
- 13:24Speaker 2: code can't sneak through.
- 13:26Speaker 1: Oh that's such relief.
- 13:27Speaker 2: And to boost performance, Doctrine caches these generated DQL queries.
- 13:31Speaker 2: It parses at once, cashes the sequel, and just swaps
- 13:34Speaker 2: the parameters next time.
- 13:35Speaker 1: Wow.
- 13:36Speaker 2: You can even use aggregate functions like count dc dot
- 13:39Speaker 2: I to return custom two dimensional arrays, like getting a
- 13:42Speaker 2: post with its total comment count.
- 13:44Speaker 1: Okay, so we've mathtered standard relations, but let's push the limits.
- 13:48Speaker 1: What happens when our data model hits a classic OOP
- 13:51Speaker 1: concept that relational databases despise.
- 13:54Speaker 2: You mean inheritance inheritance? Yea, relational databases really hate inheritance, right?
- 13:59Speaker 1: So if I have a post author and a common
- 14:01Speaker 1: author that both extend an abstract auter class, how does
- 14:06Speaker 1: doctrine handle that?
- 14:07Speaker 2: It offers three inheritance strategies. The first is mapped superclasses.
- 14:11Speaker 1: Okay, what's that?
- 14:13Speaker 2: It's good for sharing properties in your PHP code, but
- 14:16Speaker 2: at the database level, the child classes get completely separate.
- 14:20Speaker 1: Tables, so no real relation in the dB. What's the second?
- 14:23Speaker 2: Single table inheritance. It puts everyone in one massive table,
- 14:27Speaker 2: using a discriminator column usually called D type to tell
- 14:31Speaker 2: them apart.
- 14:31Speaker 1: I love my closet analogy for this one, but you're
- 14:33Speaker 1: the closets. So single table inheritance is like throwing everyone's
- 14:36Speaker 1: clothes into one giant closet, but slapping a sticky note
- 14:40Speaker 1: like the D type on them.
- 14:42Speaker 2: Highly performant, but a bit messy because.
- 14:44Speaker 1: You have a lot of empty space for properties that
- 14:47Speaker 1: don't apply to everyone exactly. But the third strategy class
- 14:50Speaker 1: table inheritance. Yeah, that's like giving everyone their own separate closet. Right.
- 14:54Speaker 2: Each class gets its own table.
- 14:56Speaker 1: But if you want to put together an outfit, you
- 14:58Speaker 1: have to open all the closets, which.
- 15:00Speaker 2: Which means your queries require massive joy and ends. It's flexible,
- 15:04Speaker 2: but much slower.
- 15:05Speaker 1: This raises an important question, which one should I actually use?
- 15:09Speaker 2: Well, it's about architectural trade offs. Single table is usually
- 15:12Speaker 2: best for performance. Class table is really reserved for highly
- 15:16Speaker 2: complex models where performance isn't the primary bottleneck.
- 15:19Speaker 1: Makes sense now real quick? Before we wrap, we have
- 15:23Speaker 1: to mention doctrine's event.
- 15:24Speaker 2: System AH life cycle events right.
- 15:27Speaker 1: Like using at hass life cycle callbacks and at pre
- 15:30Speaker 1: persist to automatically stamp a publication date right before insertion.
- 15:34Speaker 2: It's very handy, but be careful. More complex logic like
- 15:38Speaker 2: an insult event listener that scans for bad words or
- 15:41Speaker 2: emailing an author, look at that in the entity exactly,
- 15:44Speaker 2: Keep entities clean. That logic belongs in external event subscribers.
- 15:48Speaker 1: Good rule of thumb. Wow, Okay, we've journeyed from the
- 15:51Speaker 1: raw connection of PHP to the elegant abstraction of doctrine.
- 15:54Speaker 2: Today we covered a lot of ground we did.
- 15:56Speaker 1: We saw how the Entity Manager Association's DQL and advanced
- 16:00Speaker 1: inheritance make handling data an object oriented dream.
- 16:04Speaker 2: And for you listening, this means faster development, cleaner code bases,
- 16:09Speaker 2: and letting the framework handle the heavy lifting.
- 16:11Speaker 1: Yeah, database, synchronization, security, you name it. You can just
- 16:15Speaker 1: focus on building features rather than writing boilerplate sequel.
- 16:18Speaker 2: But consider this, doctrine does provide native queries and DBL
- 16:22Speaker 2: access for when you need raw database specific power, right, which.
- 16:27Speaker 1: Makes me think, As ORMs become more magical and do
- 16:31Speaker 1: more of the thinking for us, do we risk losing
- 16:33Speaker 1: our fundamental understanding of what makes it database actually performant
- 16:36Speaker 1: under the hood.
- 16:37Speaker 2: It's a valid concern.
- 16:38Speaker 1: Does the ultimate abstraction eventually abstract away our core engineering skills?
- 16:42Speaker 1: Something for you to ponder before your next deep dive.