An alternative to associative arrays in PHP

  Рет қаралды 14,390

Mateus Guimarães

Mateus Guimarães

Күн бұрын

👨‍💻 Learn Test-Driven Development with Laravel!
tddwithlaravel...
Sign up to 30 Days of Laravel 👉🏻 30daysoflarave...
👨‍💻 Sign up to my newsletter and receive PHP, JS and Laravel news in a weekly-basis:
subscribe.mate...
🎉 Party up:
/ mateusjatenee
/ mateusjatenee
/ mateusguimaraes
Thanks for watching!

Пікірлер: 122
@andyhinkle
@andyhinkle 3 ай бұрын
Nice video, Mateus! Quick joke for you-- why did the developer quit his job? Because he didn’t get arrays (a raise) 🙂
3 ай бұрын
😂
@QuintessentialDio
@QuintessentialDio 3 ай бұрын
Years of writing PHP, and i still learnt something new today, thanks lad.
3 ай бұрын
Happy to help!
@cafnix
@cafnix 3 ай бұрын
My boss, I taught you have learnt everything you need in PHP
@TotoTitus
@TotoTitus 3 ай бұрын
this has become a LOT more relevant since PHP introduced constructor-defined readonly properties. Creating value objects, DTOs whatever is now pleasant and elegant.
@chechomancr4
@chechomancr4 Ай бұрын
Min 13:20 the class "UserSetthings" can be "final readonly class UserSetthings".
@brunoggdev6305
@brunoggdev6305 3 ай бұрын
The timing for this video couldn't be better as I was literally talking about these exact points yesterday with my team. Great content man, kudos from Brazil! Also it was awesome to see u on Laracasts as well 🤩 Parabéns meu bom
3 ай бұрын
Valeu!
@ihorrud5088
@ihorrud5088 3 ай бұрын
Hi! As I understood we use just plain php classes(like UserSettings) when we want to use it internally, probably withing one layer. And if we want to pass data from controller to service or other layer we use DTO, right?
Ай бұрын
I'd suggest a DTO, yes
@alasdairmacintyre9383
@alasdairmacintyre9383 3 ай бұрын
Honestly this is a great idea and allows us do treat some classes more like structs. Objects tend to be more efficient than arrays. As other people have pointed out, this is like a DTO but without the getter methods you typically see in DTO classes. Good stuff!
3 ай бұрын
Thanks! It’d certainly be a bit easier with structs. I’m glad you enjoyed it. ✌🏻
@mkGarf
@mkGarf 3 ай бұрын
I would only add that, as a general rule, it should be understood that arrays are much more efficient in terms of memory and processing. Therefore, for any process that requires iterating over collections that can grow large, arrays should definitely be used, and objects should not be used at all. For maintainability, architecture definitely matters. Given the above, as a general rule, I would use objects as a means of communication between software components within the defined architecture, but the implementations for handling large data collections should be abstractions that use arrays behind the scenes. Let's say that algorithms, which need to be implemented correctly from the start and rarely modified, should definitely be implemented using arrays.
Ай бұрын
agreed
@nelsonmelecio
@nelsonmelecio 3 ай бұрын
How will you handle additional variable in the settings? Do you have to update the UserSettings again? Keyword: dynamic settings
3 ай бұрын
Yes, you update the class.
@marceloAK1
@marceloAK1 3 ай бұрын
Great video. I've been using this approach a lot lately. How do you work when you have an attribute in UserSettings that must be set after the object creation and need to use it inside the notifyUser function? When do you check if the attribute was set or not? Thanks so much.
3 ай бұрын
Can you exemplify? If the function takes an object as an argument, and requires property X to to be set, you can add a guard clause - e.g if ($someObject->property === null) { throw new SomeCustomException(); }
@marceloAK1
@marceloAK1 3 ай бұрын
Thanks for that, that's I wanted to know.
@abdullah.alhabal
@abdullah.alhabal 3 ай бұрын
using the DTOs and make a static method in the DTO Class like fromReqeust in this case we have the data from the request as a class, similar approach ??
@ClawHammer23
@ClawHammer23 3 ай бұрын
PHP 5.6?
@BrunoBernard-kn6vt
@BrunoBernard-kn6vt 3 ай бұрын
It is Value objects ?
3 ай бұрын
They can be VOs, but not necessarily.
@BrunoBernard-kn6vt
@BrunoBernard-kn6vt 3 ай бұрын
thanks for replying ! Ex. Let's say I have an action, i use an object instead of a array to transport the value right ? basically it reduce the need for Laravel Validators. right ?
3 ай бұрын
@@BrunoBernard-kn6vt That’d be a DTO. It doesn’t eliminate the need of a validator because you still want to validate messages at the borders (e.g HTTP). A value object would be - for example, an Email object, that could enforce the string to be a valid email, a ZipCode object, or a Money object. These would typically be used in models (through cast operations in Laravel).
@BrunoBernard-kn6vt
@BrunoBernard-kn6vt 3 ай бұрын
Thank you so much for clarifying, and if i have to organize these types objects where should I namespace it? Enums goes to Enums folder. Value Objects goes to ValueObjects folder. Objects folder perhaps?
@LewisCowles
@LewisCowles 3 ай бұрын
This is also what JS has... Array in JS is an Object with some additional symbols.
@josephmakram4342
@josephmakram4342 3 ай бұрын
Thats is why they invent the DTO concept
@tariksadiku4723
@tariksadiku4723 3 ай бұрын
DTO's are not for internal use, it is for transfering internal data in a different form for external services. For example, you might create a DTO that for oen service returns user_data => "Hello" and for another service userData => "hello"
@Fanmade1b
@Fanmade1b 3 ай бұрын
And as soon as there is additional stuff added, like validation logic (for example to allow only positive values for an integer attribute), these would be called value objects instead of DTOs. I mostly use old school arrays for simple lists where collections would be too much overhead, but then I by default add type hints. Like: /** @var array */ public function listUsers(array $users) {...} And then there are other variants, like WeakMaps, but these are a way more specific topic.
3 ай бұрын
These aren't necessarily DTOs.
@david.arl14
@david.arl14 3 ай бұрын
i do this on last my project, for Entities in laravel implemented clean architecture. and very helpful for maintaince data return from services and repositories
@ward7576
@ward7576 3 ай бұрын
Is it a mac only feature that when you type, certain keywords become italic, some not? I've tried to get it working on Ubuntu and Windows and it seems to not be working out of the box, even when correct fonts and all its' variants have been installed.
@JordanHumbertodeSouza
@JordanHumbertodeSouza 3 ай бұрын
what font is that?
@ward7576
@ward7576 3 ай бұрын
@@JordanHumbertodeSouza Anonymous Pro, in my case. All variants installed but I cannot seem to get this style working neither on Linux or Windows.
@rcnhsuailsnyfiue2
@rcnhsuailsnyfiue2 3 ай бұрын
Italic keywords are set within PhpStorm’s preferences, the font won’t make a difference if you don’t have it enabled in the IDE. Have you checked that?
3 ай бұрын
I think it’s just a PHPStorm config as someone else pointed out.
@ward7576
@ward7576 Ай бұрын
Do you mind sharing your config then? I seem to be doing something wrong (tried just setting italic for some operands).
@drugoviic
@drugoviic 3 ай бұрын
laravel throws errors when you access a key that isn't set i thought that was the default behaviour, maybe i don't know php that well
@easyvideott7505
@easyvideott7505 3 ай бұрын
This is all dependable on the context... good thing for complicated data but overkill for some simple data... Generally the video is a good hint about what can you do in PHP as a programming language. "Chose your 'weapons' wisely!"
@CottidaeSEA
@CottidaeSEA 3 ай бұрын
@@easyvideott7505 Simple data becomes complex when suddenly you need to check what to send to a function all the time. When something is added but not documented. When something is expected but not provided. A class can give you default values. An array can't. Create a class, save your colleague.
@easyvideott7505
@easyvideott7505 3 ай бұрын
@@CottidaeSEA Exactly! If you need data complex as that, surely it would be better to make a class and pass the data as an object. All I wanted to say in the previous comment is that it would be wrong to say: "Never use simple arrays in PHP, always use Class objects".
Ай бұрын
"Simple data becomes complex" - I"ll save that!
@josiasvelazquez1095
@josiasvelazquez1095 3 ай бұрын
Excellent video! What font do you use? It's awesome.
3 ай бұрын
Thank you! The font is Operator Mono.
@josiasvelazquez1095
@josiasvelazquez1095 2 ай бұрын
🫶🏻
@victoradeshayo5235
@victoradeshayo5235 3 ай бұрын
Absolutely love to do this when possible for sure. Thank you for making these contents. ❤
3 ай бұрын
Thank you for watching!
@LucasAlves-bw9ue
@LucasAlves-bw9ue 3 ай бұрын
Thats solid principles applied into php. Thats awesome!
3 ай бұрын
Glad you liked it!
@gamersunite9026
@gamersunite9026 3 ай бұрын
your username in comments doesnt render. wtf?
3 ай бұрын
Yeah I’ve noticed that as well lol
@stonedoubt
@stonedoubt 3 ай бұрын
I made a PHP “clone” of Pydantic for typed collections
@hamidrezahassani4006
@hamidrezahassani4006 3 ай бұрын
Great video. Very useful
3 ай бұрын
Glad to hear that!
@DavidSmith-ef4eh
@DavidSmith-ef4eh 3 ай бұрын
Yeah, I do this all the time. Makes refactoring much less stresfull. Also, using Propel ORM for the sam reaoson. It allows you to change the database schema without having to worry that code will break. Too bad worse ORM solutions like Eloquent are more popular than Propel. I guess PHP developers suck.
3 ай бұрын
I’ve never used Propel. I’ll take a look!
@DavidSmith-ef4eh
@DavidSmith-ef4eh 3 ай бұрын
it seems to be abandoned.. very slow updates. abandoned project. I tried to find an replacement ORM but none of them is as good as propel.
@junjunghasudungan1905
@junjunghasudungan1905 3 ай бұрын
May i assume point from this message is wrapping on the class making easier to maintance our application..
3 ай бұрын
I wouldn't call it wrapping. It is giving it constraints and behavior.
@junjunghasudungan1905
@junjunghasudungan1905 3 ай бұрын
"Thank you for clarifying my perception."
@brunonairlanda
@brunonairlanda 3 ай бұрын
nice content bro, and nice talk as well on laracon :)
3 ай бұрын
thank you!
@ricko13
@ricko13 3 ай бұрын
Mateus, I didn't watch the whole video, but it appears you're trying to do what the *spatie/laravel-data* package does, just take a look a it
Ай бұрын
It's not about a package
@fauxhound5061
@fauxhound5061 3 ай бұрын
What in the object oriented fuck is that font? Why??
@ssshenkie
@ssshenkie 3 ай бұрын
Operator Mono, it was extremly popular many years ago
3 ай бұрын
Operator Mono. I love jt
@OleksandrAndreiev
@OleksandrAndreiev 3 ай бұрын
Of course this is good approach to replace assoc arrays with objects, but it would be nice to see such approach in framework configurations instead of arrays/yaml files.
3 ай бұрын
Yeah, I’d very much enjoy that.
@kvelez
@kvelez 3 ай бұрын
Cool do more PHP videos and courses.
3 ай бұрын
will do!
@jediampm
@jediampm 3 ай бұрын
HI, thanks for the video. However did you know that PHP start as only as procedure language? only in PHP 5.0 was consider as "full-fledged OOP support,", And like i read in some comment, please dont mix up programming even they are also script languages. Exist an array of indexes ( int keys) and array assoc ( where keys are strings). If you read the official docs: "An array in PHP is actually an ordered map" however, they "This type is optimized for several different uses;". You and i dont know the cost of an object compare to an array, a data structure that was optimize for intensive and with several alternative ways of use. Why make things so complicated. if you dont have actions ( methods on object) why not just use an array? When you getting data from a DB you are getting or can get it in two way as array of arrays or as array of stdclass object. Usually i prefer as arrays. On your example, you could just do a cast to stdclass object. 😂 Just keep it simple. Not everything should be a object like other languages Depend on context 😎
3 ай бұрын
Using an stdClass is absolutely not the same thing as instantisting a proper object. An stdClass will accept anything and everything; consumers don’t know what to expect from the object, you cannot enforce types, and you cannot guarantee the object is valid at all times.
@jediampm
@jediampm 3 ай бұрын
it is object, And it is used when your are using PDO without any framework. And even with a framework when you are passing data for a view you dont have intelsense of the variables that are available. so good luck with that. PHP is not C sharp or java, even it trying to be. Sometimes simple is better.
@AllanSavolainen
@AllanSavolainen 2 ай бұрын
I would probably do this only if the class is used more than 3-5 places, if it is less, always go for array for simplicity.
Ай бұрын
It's not just about simplicity; an array doesn't enforce any types, is not automatically-refactorable, etc
@AllanSavolainen
@AllanSavolainen Ай бұрын
It is super easy to refactor when you don't have to care about types until you actually use the value to something that cares of types.
Ай бұрын
@@AllanSavolainen what I mean is that objects are recognized by IDEs and SA tools, so you can do automatic refactoring. Arrays are generic constructs that do not offer that possibility.
@khangle6872
@khangle6872 3 ай бұрын
One (still) useful usage of array is a pseudo Tuple: function doSomething(){ if (somethingWentWrong()){ return [null, new SomeBusinessException()] } return [SomeDto, null]; } function someConsumer(){ [$data, $error] = doSomething(); // } A pseudo Result monad, but until PHP had generic, Tuple will have to suffice
3 ай бұрын
Yeah, I find usages where it’s short-lived perfectly valid.
@wraithlotus
@wraithlotus 3 ай бұрын
It had never occurred to me to treat arrays as objects.
@SagorMax
@SagorMax 3 ай бұрын
Very much useful
3 ай бұрын
Glad you think so!
@zezont4
@zezont4 3 ай бұрын
✨ What a brilliant idea ! ✨ I was looking for this solution. Thank you.
3 ай бұрын
You're welcome 😊
@CottidaeSEA
@CottidaeSEA 3 ай бұрын
Honestly, I'm quite baffled that PHP devs don't use classes more. "We need to pass an array to this function" okay, so use get_object_vars? Create a toArray method? The good thing about having a class is that you can add default values to the state and easily create a copy of it, along with a strict schema to follow.
3 ай бұрын
Yeah, I’m honestly surprised by some reactions to this video, which I considered fairly mild.
@alexalex6643
@alexalex6643 Ай бұрын
yeah PHP suffers without "normal arrays"
@codyscorner1829
@codyscorner1829 3 ай бұрын
Well this is not a array. An array is one data type. When you are putting in different data types it's more a data container or table.
3 ай бұрын
It’s an associative array.
@jediampm
@jediampm 3 ай бұрын
Its only an assoc if it has keys as string, otherwise if it is a list of objects so it is an indexed array. if you have an object and cast to an array, it will be an assoc array. to sum up, for example, if you fetch from a db more that one row, than will be a list of array assoc or stdclass ( so indexed array), only a row turn into stdclass or array assoc.
@saytaimoor
@saytaimoor 3 ай бұрын
Video title is misleading. A handy solution when it come to simple read-only operations sure, but it is by no means an "alternative" to the arrays. Think about what you can achieve with arrays when it comes to data manipulation and processing. Not to mentioned numerus PHP's build in and custom-tailored functions to process data.
3 ай бұрын
You can achieve all of that still. Anything specific you're thinking about?
@MrSjcris
@MrSjcris 3 ай бұрын
too small text in console
3 ай бұрын
Thanks, I'll keep that in mind
@PaulAllsopp-rh5gb
@PaulAllsopp-rh5gb 28 күн бұрын
deletes my post...lol
@caLLLendar
@caLLLendar 3 ай бұрын
Skip the OOP and use functions to set the variables in the array. The code I am describing avoids abstraction and makes the code repetitive and cleaner. Doing so makes the code easier to understand for non-programmers, QA tools, and (local) LLMs. When the code is clean it is easy to use fully-automated systems to develop, secure, and maintain it.
3 ай бұрын
Ehhhhh
@nicolascanala9940
@nicolascanala9940 3 ай бұрын
Mmm memory... yummy yummy
@alasdairmacintyre9383
@alasdairmacintyre9383 3 ай бұрын
In general working with objects in php is more efficient than working with arrays. I just did a test where I created two collections -- one with arrays and one with classes/objects like it was shown in the video, and the objects were more efficient. This is with about 500 members of the collection and 7 datapoints / keys in each "Classes Memory Usage" => "316.41 KB" "Arrays Memory Usage" => "356.65 KB"
3 ай бұрын
It's really not a problem unless you're creating tens of thousands of objects.
@xtremescript
@xtremescript 3 ай бұрын
What you call arrays in other languages is actually vectors if you are coming from an actual programming language.
3 ай бұрын
Actually, arrays and vectors are different things. A vector is essentially a dynamic array.
@jediampm
@jediampm 3 ай бұрын
Actually, in languages like c, c sharp, java and go, vectors has a fix length / one dimension and only allow primitive types. So an array, arrayList, Map, etc, are dynamic vectors that allow more complex types and the length is dynamically updated.
3 ай бұрын
@@jediampm It’s the other way around. e.g in C# an Array has a fixed size, while a List will grow/shrink dynamically.
@jediampm
@jediampm 3 ай бұрын
your are correct, my mistake writing for too long PHP that mix up concepts like array / matrix, etc in another languages, not only C Sharp.
@PaulAllsopp-rh5gb
@PaulAllsopp-rh5gb 28 күн бұрын
You have no idea what you're talking about
@startfirebg
@startfirebg 3 ай бұрын
Actually, this is not entirely true and you unfortunately are misleading viewers. Of course you do have arrays: $array = ['apples', 'grapes', 'bananas']; - You didn't mentioned that one. Even you have nice in_array($searchWhat, $array); You didn't covered array_map() and array_map_recursive() that you can actually may use to check your entire N-level array. The other thing I think you presented wrongly (It is not intentional, I know) is mapping the array keys into class parameters (?!?). Arrays are a data structures. They carry, combine and transform information. Arrays are not meant to be used like that. If you refer Python for example, you will have to admit, that actually PHP has the half of Python's data structures: list, dictionay, and misses the other two.
3 ай бұрын
Yes, you do have “regular arrays”, as I mentioned in the video - they’re both implemented as a hash maps. ‘apples’, ‘grapes’, ‘bananas’, are, really, associative arrays with integer keys in PHP - hence why you can have an array mixed with both integer and string keys. In your example, you could do $data[‘foo] = ‘bar’, and you’d get [0, 1, 2, ‘foo’]. Check out my video on how arrays function internally in PHP. I’m honestly not sure what you’re trying to imply with this comment - I didn’t cover any array functions because this video is about associative arrays, not lists.
@startfirebg
@startfirebg 3 ай бұрын
I imply nothing. I just listened at the beginning what you're explaining, and how the video is going. I do not want to offend you, nor trying to put bad sign under your video. I just hoped to see something fully helpful from the start to the end :) Cheers.
@flixtechs
@flixtechs 3 ай бұрын
I think the problem is you're using a mental model from other programming languages
3 ай бұрын
How would you do it?
@alasdairmacintyre9383
@alasdairmacintyre9383 3 ай бұрын
It is not a bad idea to try and implement concepts that exist in other programming languages but aren't in whatever programming language you're using
@smith-play
@smith-play 3 ай бұрын
Nice, Metaus just discovered DTOs (very "useful" for 2024). Ugly font btw
3 ай бұрын
ok man
@smith-play
@smith-play 3 ай бұрын
No offence, I mean you should name things as they been called by devs. DTOs are important for newbies but from beginning they should know terminology well
3 ай бұрын
@@smith-play these are not necessarily DTOs. There’s a separate video on my channel about DTOs
@jirikolapa4292
@jirikolapa4292 3 ай бұрын
What do you call them? And do you just put them in same namespace as your dtos?
3 ай бұрын
@@jirikolapa4292 I just call them objects. Depending on the usage it could be a DTO, yes. I do not group things by type, so there’s not a specific folder for them - they’d be in the same namespace as other classes from that context.
Why is Javascript so advanced yet behind?
9:05
Mateus Guimarães
Рет қаралды 970
Laravel + Service Pattern + DTOs = ❤️❤️❤️
17:52
Przemysław Przyłucki
Рет қаралды 54 М.
1% vs 100% #beatbox #tiktok
01:10
BeatboxJCOP
Рет қаралды 67 МЛН
How to treat Acne💉
00:31
ISSEI / いっせい
Рет қаралды 108 МЛН
The most powerful way to use Eloquent
11:51
Mateus Guimarães
Рет қаралды 5 М.
Using Generics with PHP
25:55
Laracasts
Рет қаралды 15 М.
How associative arrays work internally
19:00
Mateus Guimarães
Рет қаралды 1,7 М.
What's New and Exciting in PHP 8.4
9:58
php[architect]
Рет қаралды 16 М.
Intro to the Meson Build System
9:52
durk
Рет қаралды 1,3 М.
PHP-FPM vs Swoole execution model
15:36
Mateus Guimarães
Рет қаралды 7 М.
I built an app using a single index.php file, here's how it went
32:42
Andrew Schmelyun
Рет қаралды 91 М.
Trying out the JIT in PHP 8.4
29:29
PHP Annotated
Рет қаралды 8 М.
When to use Traits, Interfaces, and Abstract Classes in PHP
15:08
Andrew Schmelyun
Рет қаралды 24 М.
PHP on the frontend! No more Javascript!
14:47
Aaron Francis
Рет қаралды 127 М.